@kubb/adapter-oas 5.0.0-alpha.13 → 5.0.0-alpha.15
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 +19 -75
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +0 -17
- package/dist/index.js +19 -75
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/adapter.ts +2 -4
- package/src/oas/Oas.ts +2 -10
- package/src/oas/utils.ts +7 -8
- package/src/parser.ts +8 -27
- package/src/types.ts +0 -11
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#options","#transformParam","#eachParam","#options","#applyDiscriminatorInheritance","#setDiscriminator","#getResponseBodyFactory"],"sources":["../src/constants.ts","../src/oas/resolveServerUrl.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/names.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/oas/Oas.ts","../src/oas/utils.ts","../src/utils.ts","../src/parser.ts","../src/adapter.ts"],"sourcesContent":["import type { SchemaType } from '@kubb/ast/types'\nimport type { HttpMethods as OASHttpMethods } from 'oas/types'\nimport type { ParserOptions } from './types.ts'\n\n/**\n * Default values for all `Options` fields.\n */\nexport const DEFAULT_PARSER_OPTIONS = {\n dateType: 'string',\n integerType: 'number',\n unknownType: 'any',\n emptySchemaType: 'any',\n enumSuffix: 'enum',\n} as const satisfies ParserOptions\n\n/**\n * OpenAPI version string written into merged document stubs.\n */\nexport const MERGE_OPENAPI_VERSION = '3.0.0' as const\n\n/**\n * Fallback `info.title` used when merging multiple API documents.\n */\nexport const MERGE_DEFAULT_TITLE = 'Merged API' as const\n\n/**\n * Fallback `info.version` used when merging multiple API documents.\n */\nexport const MERGE_DEFAULT_VERSION = '1.0.0' as const\n\n/**\n * JSON Schema keywords that indicate structural composition.\n * A schema fragment containing any of these keys must not be inlined into its\n * parent during `allOf` flattening — it carries semantic meaning of its own.\n */\nexport const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)\n\n/**\n * Maps OAS/JSON Schema `format` strings to their Kubb `SchemaType` equivalents.\n *\n * Only formats that need a type different from the raw OAS `type` are listed.\n * `int64`, `date-time`, `date`, and `time` are handled separately because their\n * mapping depends on runtime parser options.\n *\n * Note: `ipv4`, `ipv6`, and `hostname` map to `'url'` — the closest supported\n * scalar type in the Kubb AST, even though these are not strictly URLs.\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: 'url',\n ipv6: 'url',\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, SchemaType>\n\n/**\n * Exhaustive list of media types that Kubb recognizes.\n */\nexport const knownMediaTypes = new Set([\n 'application/json',\n 'application/xml',\n 'application/x-www-form-urlencoded',\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'application/graphql',\n 'multipart/form-data',\n 'text/plain',\n 'text/html',\n 'text/csv',\n 'text/xml',\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/svg+xml',\n 'audio/mpeg',\n 'video/mp4',\n] as const)\n\n/**\n * Vendor extension keys used to attach human-readable labels to enum values.\n * Checked in priority order: the first key found wins.\n */\nexport const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const\n\n/**\n * Scalar primitive schema types used for union member simplification.\n */\nexport const SCALAR_PRIMITIVE_TYPES = new Set(['string', 'number', 'integer', 'bigint', 'boolean'] as const)\n\n/**\n * Canonical HTTP method names for the Kubb OAS layer.\n * Keys are uppercase (used in generated code); values are the lowercase strings\n * that the `oas` library uses internally.\n *\n * TODO(v5): remove — use `httpMethods` from `@kubb/ast`\n */\nexport const httpMethods = {\n GET: 'get',\n POST: 'post',\n PUT: 'put',\n PATCH: 'patch',\n DELETE: 'delete',\n HEAD: 'head',\n OPTIONS: 'options',\n TRACE: 'trace',\n} as const satisfies Record<Uppercase<OASHttpMethods>, OASHttpMethods>\n","/**\n * Models one variable definition in an OpenAPI server object.\n */\ntype ServerVariable = {\n default?: string | number\n enum?: (string | number)[]\n}\n\n/**\n * Minimal shape of an OpenAPI server object.\n */\ntype ServerObject = {\n url: string\n variables?: Record<string, ServerVariable>\n}\n\n/**\n * Resolves an OpenAPI server URL by substituting `{variable}` placeholders.\n *\n * Resolution priority per variable:\n * 1. `overrides[key]` — caller-supplied value.\n * 2. `variable.default` — spec-defined default, coerced to `string`.\n * 3. Variable is left unreplaced when neither is available.\n *\n * Throws when an `overrides` value is not present in the variable's `enum` list.\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 Error(`Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`)\n }\n\n url = url.replaceAll(`{${key}}`, value)\n }\n\n return url\n}\n","type Options = {\n /** When `true`, dot-separated segments are split on `.` and joined with `/` after casing. */\n isFile?: boolean\n /** Text prepended before casing is applied. */\n prefix?: string\n /** Text appended before casing is applied. */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Splits `text` on `.` and applies `transformPart` to each segment.\n * The last segment receives `isLast = true`, all earlier segments receive `false`.\n * Segments are joined with `/` to form a file path.\n *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\n\n/**\n * Converts `text` to camelCase.\n * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n *\n * @example\n * camelCase('hello-world') // 'helloWorld'\n * camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n *\n * @example\n * pascalCase('hello-world') // 'HelloWorld'\n * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","/**\n * Returns a unique name by appending an incrementing numeric suffix when the name has already been used.\n * Mutates `data` in-place as a usage counter so subsequent calls remain consistent.\n *\n * @example\n * const seen: Record<string, number> = {}\n * getUniqueName('Foo', seen) // 'Foo'\n * getUniqueName('Foo', seen) // 'Foo2'\n * getUniqueName('Foo', seen) // 'Foo3'\n */\nexport function getUniqueName(originalName: string, data: Record<string, number>): string {\n let used = data[originalName] || 0\n if (used) {\n data[originalName] = ++used\n originalName += used\n }\n data[originalName] = 1\n return originalName\n}\n\n/**\n * Registers `originalName` in `data` without altering the returned name.\n * Use this when you need to track usage frequency but always emit the original identifier.\n */\nexport function setUniqueName(originalName: string, data: Record<string, number>): string {\n let used = data[originalName] || 0\n if (used) {\n data[originalName] = ++used\n return originalName\n }\n data[originalName] = 1\n return originalName\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 a word with `_` when it is a reserved JavaScript/Java identifier\n * or starts with a digit.\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 */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /** The resolved URL string (Express-style or template literal, depending on context). */\n url: string\n /** Extracted path parameters as a key-value map, or `undefined` when the path has none. */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /** Controls whether the `url` is rendered as an Express path or a template literal. Defaults to `'path'`. */\n type?: 'path' | 'template'\n /** Optional transform applied to each extracted parameter name. */\n replacer?: (pathParam: string) => string\n /** When `true`, the result is serialized to a string expression instead of a plain object. */\n stringify?: boolean\n}\n\n/** Supported identifier casing strategies for path parameters. */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /** Casing strategy applied to path parameter names. Defaults to the original identifier. */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /** The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`. */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`). */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set. */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters. */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /** Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name. */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import jsonpointer from 'jsonpointer'\nimport BaseOas from 'oas'\nimport type { ParameterObject } from 'oas/types'\nimport { matchesMimeType } from 'oas/utils'\nimport type { contentType, DiscriminatorObject, Document, MediaTypeObject, Operation, ReferenceObject, ResponseObject, SchemaObject } from './types.ts'\nimport {\n extractSchemaFromContent,\n flattenSchema,\n isDiscriminator,\n isReference,\n legacyResolve,\n resolveCollisions,\n type SchemaWithMetadata,\n sortSchemas,\n validate,\n} from './utils.ts'\n\n/**\n * Prefix used to create synthetic `$ref` values for anonymous (inline) discriminator schemas.\n * The suffix is the schema index within the discriminator's `oneOf`/`anyOf` array.\n * @example `#kubb-inline-0`\n */\nconst KUBB_INLINE_REF_PREFIX = '#kubb-inline-'\n\ntype OasOptions = {\n contentType?: contentType\n discriminator?: 'strict' | 'inherit'\n /**\n * Resolve name collisions when schemas from different components share the same name (case-insensitive).\n * @default false\n */\n collisionDetection?: boolean\n}\n\nexport class Oas extends BaseOas {\n #options: OasOptions = {\n discriminator: 'strict',\n }\n document: Document\n\n constructor(document: Document) {\n super(document, undefined)\n\n this.document = document\n }\n\n setOptions(options: OasOptions) {\n this.#options = {\n ...this.#options,\n ...options,\n }\n\n if (this.#options.discriminator === 'inherit') {\n this.#applyDiscriminatorInheritance()\n }\n }\n\n get options(): OasOptions {\n return this.#options\n }\n\n get<T = unknown>($ref: string): T | null {\n const origRef = $ref\n $ref = $ref.trim()\n if ($ref === '') {\n return null\n }\n if ($ref.startsWith('#')) {\n $ref = globalThis.decodeURIComponent($ref.substring(1))\n } else {\n return null\n }\n const current = jsonpointer.get(this.api, $ref)\n\n if (!current) {\n throw new Error(`Could not find a definition for ${origRef}.`)\n }\n return current as T\n }\n\n getKey($ref: string) {\n const key = $ref.split('/').pop()\n return key === '' ? undefined : key\n }\n set($ref: string, value: unknown) {\n $ref = $ref.trim()\n if ($ref === '') {\n return false\n }\n if ($ref.startsWith('#')) {\n $ref = globalThis.decodeURIComponent($ref.substring(1))\n\n jsonpointer.set(this.api, $ref, value)\n }\n }\n\n #setDiscriminator(schema: SchemaObject & { discriminator: DiscriminatorObject }): void {\n const { mapping = {}, propertyName } = schema.discriminator\n\n if (this.#options.discriminator === 'inherit') {\n Object.entries(mapping).forEach(([mappingKey, mappingValue]) => {\n if (mappingValue) {\n const childSchema = this.get<any>(mappingValue)\n if (!childSchema) {\n return\n }\n\n if (!childSchema.properties) {\n childSchema.properties = {}\n }\n\n const property = childSchema.properties[propertyName] as SchemaObject\n\n if (childSchema.properties) {\n childSchema.properties[propertyName] = {\n ...((childSchema.properties ? childSchema.properties[propertyName] : {}) as SchemaObject),\n enum: [...(property?.enum?.filter((value) => value !== mappingKey) ?? []), mappingKey],\n }\n\n childSchema.required =\n typeof childSchema.required === 'boolean' ? childSchema.required : [...new Set([...(childSchema.required ?? []), propertyName])]\n\n this.set(mappingValue, childSchema)\n }\n }\n })\n }\n }\n\n getDiscriminator(schema: SchemaObject | null): DiscriminatorObject | null {\n if (!isDiscriminator(schema) || !schema) {\n return null\n }\n\n const { mapping = {}, propertyName } = schema.discriminator\n\n /**\n * Helper to extract discriminator value from a schema.\n * Checks in order:\n * 1. Extension property matching propertyName (e.g., x-linode-ref-name)\n * 2. Property with const value\n * 3. Property with single enum value\n * 4. Title as fallback\n */\n const getDiscriminatorValue = (schema: SchemaObject | null): string | null => {\n if (!schema) {\n return null\n }\n\n // Check extension properties first (e.g., x-linode-ref-name)\n // Only check if propertyName starts with 'x-' to avoid conflicts with standard properties\n if (propertyName.startsWith('x-')) {\n const extensionValue = (schema as Record<string, unknown>)[propertyName]\n if (extensionValue && typeof extensionValue === 'string') {\n return extensionValue\n }\n }\n\n // Check if property has const value\n const propertySchema = schema.properties?.[propertyName] as SchemaObject\n if (propertySchema && 'const' in propertySchema && propertySchema.const !== undefined) {\n return String(propertySchema.const)\n }\n\n // Check if property has single enum value\n if (propertySchema && propertySchema.enum?.length === 1) {\n return String(propertySchema.enum[0])\n }\n\n // Fallback to title if available\n return schema.title || null\n }\n\n /**\n * Process oneOf/anyOf items to build mapping.\n * Handles both $ref and inline schemas.\n */\n const processSchemas = (schemas: Array<SchemaObject>, existingMapping: Record<string, string>) => {\n schemas.forEach((schemaItem, index) => {\n if (isReference(schemaItem)) {\n // Handle $ref case\n const key = this.getKey(schemaItem.$ref)\n\n try {\n const refSchema = this.get<SchemaObject>(schemaItem.$ref)\n const discriminatorValue = getDiscriminatorValue(refSchema)\n const canAdd = key && !Object.values(existingMapping).includes(schemaItem.$ref)\n\n if (canAdd && discriminatorValue) {\n existingMapping[discriminatorValue] = schemaItem.$ref\n } else if (canAdd) {\n existingMapping[key] = schemaItem.$ref\n }\n } catch (_error) {\n // If we can't resolve the reference, skip it and use the key as fallback\n if (key && !Object.values(existingMapping).includes(schemaItem.$ref)) {\n existingMapping[key] = schemaItem.$ref\n }\n }\n } else {\n // Handle inline schema case\n const inlineSchema = schemaItem as SchemaObject\n const discriminatorValue = getDiscriminatorValue(inlineSchema)\n\n if (discriminatorValue) {\n // Create a synthetic ref for inline schemas using index\n // The value points to the inline schema itself via a special marker\n existingMapping[discriminatorValue] = `${KUBB_INLINE_REF_PREFIX}${index}`\n }\n }\n })\n }\n\n // Process oneOf schemas\n if (schema.oneOf) {\n processSchemas(schema.oneOf as Array<SchemaObject>, mapping)\n }\n\n // Process anyOf schemas\n if (schema.anyOf) {\n processSchemas(schema.anyOf as Array<SchemaObject>, mapping)\n }\n\n return {\n ...schema.discriminator,\n mapping,\n }\n }\n\n // TODO add better typing\n dereferenceWithRef<T = unknown>(schema?: T): T {\n if (isReference(schema)) {\n return {\n ...schema,\n ...this.get(schema.$ref),\n $ref: schema.$ref,\n }\n }\n\n return schema as T\n }\n\n #applyDiscriminatorInheritance() {\n const components = this.api.components\n if (!components?.schemas) {\n return\n }\n\n const visited = new WeakSet<object>()\n const enqueue = (value: unknown) => {\n if (!value) {\n return\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n enqueue(item)\n }\n return\n }\n\n if (typeof value === 'object') {\n visit(value as SchemaObject)\n }\n }\n\n const visit = (schema?: SchemaObject | ReferenceObject | null) => {\n if (!schema || typeof schema !== 'object') {\n return\n }\n\n if (isReference(schema)) {\n visit(this.get(schema.$ref) as SchemaObject)\n return\n }\n\n const schemaObject = schema as SchemaObject\n\n if (visited.has(schemaObject as object)) {\n return\n }\n\n visited.add(schemaObject as object)\n\n if (isDiscriminator(schemaObject)) {\n this.#setDiscriminator(schemaObject)\n }\n\n if ('allOf' in schemaObject) {\n enqueue(schemaObject.allOf)\n }\n if ('oneOf' in schemaObject) {\n enqueue(schemaObject.oneOf)\n }\n if ('anyOf' in schemaObject) {\n enqueue(schemaObject.anyOf)\n }\n if ('not' in schemaObject) {\n enqueue(schemaObject.not)\n }\n if ('items' in schemaObject) {\n enqueue(schemaObject.items)\n }\n if ('prefixItems' in schemaObject) {\n enqueue(schemaObject.prefixItems)\n }\n\n if (schemaObject.properties) {\n enqueue(Object.values(schemaObject.properties))\n }\n\n if (schemaObject.additionalProperties && typeof schemaObject.additionalProperties === 'object') {\n enqueue(schemaObject.additionalProperties)\n }\n }\n\n for (const schema of Object.values(components.schemas)) {\n visit(schema as SchemaObject)\n }\n }\n\n /**\n * Oas does not have a getResponseBody(contentType)\n */\n #getResponseBodyFactory(responseBody: boolean | ResponseObject): (contentType?: string) => MediaTypeObject | false | [string, MediaTypeObject, ...string[]] {\n function hasResponseBody(res = responseBody): res is ResponseObject {\n return !!res\n }\n\n return (contentType) => {\n if (!hasResponseBody(responseBody)) {\n return false\n }\n\n if (isReference(responseBody)) {\n // If the request body is still a `$ref` pointer we should return false because this library\n // assumes that you've run dereferencing beforehand.\n return false\n }\n\n if (!responseBody.content) {\n return false\n }\n\n if (contentType) {\n if (!(contentType in responseBody.content)) {\n return false\n }\n\n return responseBody.content[contentType]!\n }\n\n // Since no media type was supplied we need to find either the first JSON-like media type that\n // we've got, or the first available of anything else if no JSON-like media types are present.\n let availableContentType: string | undefined\n const contentTypes = Object.keys(responseBody.content)\n contentTypes.forEach((mt: string) => {\n if (!availableContentType && matchesMimeType.json(mt)) {\n availableContentType = mt\n }\n })\n\n if (!availableContentType) {\n contentTypes.forEach((mt: string) => {\n if (!availableContentType) {\n availableContentType = mt\n }\n })\n }\n\n if (availableContentType) {\n return [availableContentType, responseBody.content[availableContentType]!, ...(responseBody.description ? [responseBody.description] : [])]\n }\n\n return false\n }\n }\n\n getResponseSchema(operation: Operation, statusCode: string | number): SchemaObject {\n if (operation.schema.responses) {\n Object.keys(operation.schema.responses).forEach((key) => {\n const schema = operation.schema.responses![key]\n const $ref = isReference(schema) ? schema.$ref : undefined\n\n if (schema && $ref) {\n operation.schema.responses![key] = this.get<any>($ref)\n }\n })\n }\n\n const getResponseBody = this.#getResponseBodyFactory(operation.getResponseByStatusCode(statusCode))\n\n const { contentType } = this.#options\n const responseBody = getResponseBody(contentType)\n\n if (responseBody === false) {\n // return empty object because response will always be defined(request does not need a body)\n return {}\n }\n\n const schema = Array.isArray(responseBody) ? responseBody[1].schema : responseBody.schema\n\n if (!schema) {\n // return empty object because response will always be defined(request does not need a body)\n\n return {}\n }\n\n return this.dereferenceWithRef(schema)\n }\n\n getRequestSchema(operation: Operation): SchemaObject | undefined {\n const { contentType } = this.#options\n\n if (operation.schema.requestBody) {\n operation.schema.requestBody = this.dereferenceWithRef(operation.schema.requestBody)\n }\n\n const requestBody = operation.getRequestBody(contentType)\n\n if (requestBody === false) {\n return undefined\n }\n\n const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema\n\n if (!schema) {\n return undefined\n }\n\n return this.dereferenceWithRef(schema)\n }\n\n /**\n * Returns all resolved parameters for an operation, merging path-level and operation-level\n * parameters and deduplicating by `in:name` (operation-level takes precedence).\n *\n * oas v31+ filters out `$ref` parameters in `getParameters()`, so this method accesses the\n * raw `operation.schema.parameters` and path-item parameters directly and resolves `$ref`\n * pointers via `dereferenceWithRef` to preserve backward compatibility.\n */\n getParameters(operation: Operation): Array<ParameterObject> {\n const resolveParams = (params: unknown[]): Array<ParameterObject> =>\n params.map((p) => this.dereferenceWithRef(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 = this.api?.paths?.[operation.path]\n const pathLevelParams = resolveParams(pathItem && !isReference(pathItem) && pathItem.parameters ? pathItem.parameters : [])\n\n // Deduplicate: operation-level parameters override path-level ones with the same name+in\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\n getParametersSchema(operation: Operation, inKey: 'path' | 'query' | 'header'): SchemaObject | null {\n const { contentType = operation.getContentType() } = this.#options\n\n const params = this.getParameters(operation).filter((v) => v.in === inKey)\n\n if (!params.length) {\n return null\n }\n\n return params.reduce(\n (schema, pathParameters) => {\n const property = (pathParameters.content?.[contentType]?.schema ?? (pathParameters.schema as SchemaObject)) as SchemaObject | null\n const required =\n typeof schema.required === 'boolean'\n ? schema.required\n : [...(schema.required || []), pathParameters.required ? pathParameters.name : undefined].filter(Boolean)\n\n // Handle explode=true with style=form for object with additionalProperties\n // According to OpenAPI spec, when explode is true, object properties are flattened\n const getDefaultStyle = (location: string): string => {\n if (location === 'query') return 'form'\n if (location === 'path') return 'simple'\n return 'simple'\n }\n const style = pathParameters.style || getDefaultStyle(inKey)\n const explode = pathParameters.explode !== undefined ? pathParameters.explode : style === 'form'\n\n if (\n inKey === 'query' &&\n style === 'form' &&\n explode === true &&\n property?.type === 'object' &&\n property?.additionalProperties &&\n !property?.properties\n ) {\n // When explode is true for an object with only additionalProperties,\n // flatten it to the root level by merging additionalProperties with existing schema.\n // This preserves other query parameters while allowing dynamic key-value pairs.\n return {\n ...schema,\n description: pathParameters.description || schema.description,\n deprecated: schema.deprecated,\n example: property.example || schema.example,\n additionalProperties: property.additionalProperties,\n } as SchemaObject\n }\n\n return {\n ...schema,\n description: schema.description,\n deprecated: schema.deprecated,\n example: schema.example,\n required,\n properties: {\n ...schema.properties,\n [pathParameters.name]: {\n description: pathParameters.description,\n ...property,\n },\n },\n } as SchemaObject\n },\n { type: 'object', required: [], properties: {} } as SchemaObject,\n )\n }\n\n async validate() {\n return validate(this.api)\n }\n\n flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n return flattenSchema(schema)\n }\n\n /**\n * Get schemas from OpenAPI components (schemas, responses, requestBodies).\n * Returns schemas in dependency order along with name mapping for collision resolution.\n */\n getSchemas(options: { contentType?: contentType; includes?: Array<'schemas' | 'responses' | 'requestBodies'>; collisionDetection?: boolean } = {}): {\n schemas: Record<string, SchemaObject>\n nameMapping: Map<string, string>\n } {\n const contentType = options.contentType ?? this.#options.contentType\n const includes = options.includes ?? ['schemas', 'requestBodies', 'responses']\n const shouldResolveCollisions = options.collisionDetection ?? this.#options.collisionDetection ?? false\n\n const components = this.getDefinition().components\n const schemasWithMeta: SchemaWithMetadata[] = []\n\n // Collect schemas from components\n if (includes.includes('schemas')) {\n const componentSchemas = (components?.schemas as Record<string, SchemaObject>) || {}\n for (const [name, schemaObject] of Object.entries(componentSchemas)) {\n // Resolve schema if it's a $ref (can happen when the bundler deduplicates schemas\n // referenced from multiple external files). Without this, a $ref schema would be\n // parsed as a reference to itself, generating `z.lazy(() => schemaName)`.\n let schema = schemaObject\n if (isReference(schemaObject)) {\n const resolved = this.get<SchemaObject>(schemaObject.$ref)\n if (resolved && !isReference(resolved)) {\n schema = resolved\n }\n }\n schemasWithMeta.push({ schema, source: 'schemas', originalName: name })\n }\n }\n\n if (includes.includes('responses')) {\n const responses = components?.responses || {}\n for (const [name, response] of Object.entries(responses)) {\n const responseObject = response as ResponseObject\n const schema = extractSchemaFromContent(responseObject.content, contentType)\n if (schema) {\n // Resolve schema if it's a $ref (can happen when the bundler deduplicates schemas\n // referenced from multiple external files). Without this, a $ref schema would be\n // parsed as a reference to itself, generating `z.lazy(() => schemaName)`.\n let resolvedSchema = schema\n if (isReference(schema)) {\n const resolved = this.get<SchemaObject>(schema.$ref)\n if (resolved && !isReference(resolved)) {\n resolvedSchema = resolved\n }\n }\n schemasWithMeta.push({ schema: resolvedSchema, source: 'responses', originalName: name })\n }\n }\n }\n\n if (includes.includes('requestBodies')) {\n const requestBodies = components?.requestBodies || {}\n for (const [name, request] of Object.entries(requestBodies)) {\n const requestObject = request as { content?: Record<string, unknown> }\n const schema = extractSchemaFromContent(requestObject.content, contentType)\n if (schema) {\n // Resolve schema if it's a $ref (can happen when the bundler deduplicates schemas\n // referenced from multiple external files). Without this, a $ref schema would be\n // parsed as a reference to itself, generating `z.lazy(() => schemaName)`.\n let resolvedSchema = schema\n if (isReference(schema)) {\n const resolved = this.get<SchemaObject>(schema.$ref)\n if (resolved && !isReference(resolved)) {\n resolvedSchema = resolved\n }\n }\n schemasWithMeta.push({ schema: resolvedSchema, source: 'requestBodies', originalName: name })\n }\n }\n }\n\n // Apply collision resolution only if enabled\n const { schemas, nameMapping } = shouldResolveCollisions ? resolveCollisions(schemasWithMeta) : legacyResolve(schemasWithMeta)\n\n return {\n schemas: sortSchemas(schemas),\n nameMapping,\n }\n }\n}\n","import path from 'node:path'\nimport { pascalCase, URLPath } from '@internals/utils'\nimport type { Config } from '@kubb/core'\nimport { bundle, loadConfig } from '@redocly/openapi-core'\nimport yaml from '@stoplight/yaml'\nimport { isRef } from 'oas/types'\nimport OASNormalize from 'oas-normalize'\nimport type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\nimport { isPlainObject, mergeDeep } from 'remeda'\nimport swagger2openapi from 'swagger2openapi'\nimport { MERGE_DEFAULT_TITLE, MERGE_DEFAULT_VERSION, MERGE_OPENAPI_VERSION, structuralKeys } from '../constants.ts'\nimport { Oas } from './Oas.ts'\nimport type { contentType, Document, SchemaObject } from './types.ts'\n\n/**\n * Narrows `doc` to a Swagger 2.0 document.\n * Swagger 2.0 documents do not have an `openapi` version key.\n */\nexport function isOpenApiV2Document(doc: unknown): doc is OpenAPIV2.Document {\n return !!doc && isPlainObject(doc) && !('openapi' in doc)\n}\n\n/**\n * Narrows `doc` to an OpenAPI 3.x document.\n * Any document that has an `openapi` key is considered 3.x (including 3.1).\n */\nexport function isOpenApiV3Document(doc: unknown): doc is OpenAPIV3.Document {\n return !!doc && isPlainObject(doc) && 'openapi' in doc\n}\n\n/**\n * Narrows `doc` to an OpenAPI 3.1 document by checking the version prefix.\n */\nexport function isOpenApiV3_1Document(doc: unknown): doc is OpenAPIV3_1.Document {\n return !!doc && isPlainObject(doc) && 'openapi' in (doc as object) && (doc as { openapi: string }).openapi.startsWith('3.1')\n}\n\n/**\n * Returns `true` when a schema should be treated as nullable.\n *\n * Covers three nullable signals across OAS versions:\n * - OAS 3.0: `nullable: true` or the vendor extension `x-nullable: true`.\n * - OAS 3.1 / JSON Schema: `type: 'null'` or `type: ['null', ...]` (multi-type array).\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 * Narrows `obj` to an OpenAPI `$ref` pointer object.\n * Delegates to the `oas` package's own `isRef` helper.\n */\nexport function isReference(obj?: unknown): obj is OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject {\n return !!obj && isRef(obj as object)\n}\n\n/**\n * Returns `true` when `obj` is a schema that carries a structured OAS 3.x `discriminator`\n * object — as opposed to a plain-string discriminator found in some Swagger 2 specs.\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: OpenAPIV3.DiscriminatorObject } {\n const record = obj as Record<string, unknown>\n return !!obj && !!record['discriminator'] && typeof record['discriminator'] !== 'string'\n}\n\n/**\n * Loads, dereferences, and wraps a raw OpenAPI document into an `Oas` instance.\n *\n * When given a file path string with `canBundle: true` (the default), Redocly's\n * bundler resolves all external `$ref`s first. Swagger 2.0 documents are\n * automatically up-converted to OpenAPI 3.0 via `swagger2openapi`.\n */\nexport async function parse(\n pathOrApi: string | Document,\n { oasClass = Oas, canBundle = true, enablePaths = true }: { oasClass?: typeof Oas; canBundle?: boolean; enablePaths?: boolean } = {},\n): Promise<Oas> {\n if (typeof pathOrApi === 'string' && canBundle) {\n const config = await loadConfig()\n const bundleResults = await bundle({ ref: pathOrApi, config, base: pathOrApi })\n\n return parse(bundleResults.bundle.parsed as string, { oasClass, canBundle, enablePaths })\n }\n\n const oasNormalize = new OASNormalize(pathOrApi, {\n enablePaths,\n colorizeErrors: true,\n })\n const document = (await oasNormalize.load()) as Document\n\n if (isOpenApiV2Document(document)) {\n const { openapi } = await swagger2openapi.convertObj(document, {\n anchors: true,\n })\n\n return new oasClass(openapi as Document)\n }\n\n return new oasClass(document)\n}\n\n/**\n * Deep-merges multiple OpenAPI documents into a single `Oas` instance.\n *\n * Each document is parsed independently (without path dereferencing) and then\n * recursively merged using `remeda`'s `mergeDeep`. The result is re-parsed so\n * the returned `Oas` instance is fully initialized.\n *\n * Throws when the input array is empty — at least one document is required.\n */\nexport async function merge(pathOrApi: Array<string | Document>, { oasClass = Oas }: { oasClass?: typeof Oas } = {}): Promise<Oas> {\n const instances = await Promise.all(pathOrApi.map((p) => parse(p, { oasClass, enablePaths: false, canBundle: false })))\n\n if (instances.length === 0) {\n throw new Error('No OAS instances provided for merging.')\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 = instances.reduce((acc, current) => mergeDeep(acc, current.document as Document), seed)\n\n return parse(merged, { oasClass })\n}\n\n/**\n * Constructs an `Oas` instance from a Kubb `Config` object.\n *\n * Handles all three input forms supported by `Config`:\n * - `data` — an inline YAML string, JSON string, or pre-parsed object.\n * - Array — multiple file paths that are deep-merged via {@link merge}.\n * - `path` — a local file path or a remote URL.\n */\nexport function parseFromConfig(config: Config, oasClass: typeof Oas = Oas): Promise<Oas> {\n if ('data' in config.input) {\n if (typeof config.input.data === 'object') {\n return parse(structuredClone(config.input.data) as Document, { oasClass })\n }\n\n try {\n const api: string = yaml.parse(config.input.data as string)\n return parse(api, { oasClass })\n } catch {\n return parse(config.input.data as string, { oasClass })\n }\n }\n\n if (Array.isArray(config.input)) {\n return merge(\n config.input.map((input) => path.resolve(config.root, input.path)),\n { oasClass },\n )\n }\n\n if (new URLPath(config.input.path).isURL) {\n return parse(config.input.path, { oasClass })\n }\n\n return parse(path.resolve(config.root, config.input.path), { oasClass })\n}\n\n/**\n * Flattens a single-member or keyword-only `allOf` into its parent schema.\n *\n * Flattening is only performed when every `allOf` member is a \"plain fragment\" —\n * i.e. contains no structural composition keywords (see `structuralKeys`) and no\n * `$ref`. When any member carries structural meaning, the schema is returned unchanged.\n *\n * Keyword values from allOf members are merged into the parent on a first-write basis:\n * outer schema values always win over fragment values.\n */\nexport function flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null\n if (schema.allOf.some((item) => isRef(item))) return schema\n\n const isPlainFragment = (item: SchemaObject) => !Object.keys(item).some((key) => structuralKeys.has(key as 'properties'))\n if (!schema.allOf.every((item) => isPlainFragment(item as SchemaObject))) return schema\n\n const merged: SchemaObject = { ...schema }\n delete merged.allOf\n\n for (const fragment of schema.allOf as SchemaObject[]) {\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 * Validates an OpenAPI document using `oas-normalize`.\n * Enables path validation and colorized error output.\n */\nexport async function validate(document: Document) {\n const oasNormalize = new OASNormalize(document, {\n enablePaths: true,\n colorizeErrors: true,\n })\n\n return oasNormalize.validate({\n parser: {\n validate: {\n errors: { colorize: true },\n },\n },\n })\n}\n\n/**\n * Discriminates the three component sources Kubb reads schemas from.\n */\ntype SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'\n\nexport type SchemaWithMetadata = {\n schema: SchemaObject\n source: SchemaSourceMode\n originalName: string\n}\n\ntype GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n nameMapping: Map<string, string>\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` refs.\n * Used by `sortSchemas` to build the dependency graph.\n */\nfunction collectRefs(schema: unknown, refs = new Set<string>()): Set<string> {\n if (Array.isArray(schema)) {\n for (const item of schema) collectRefs(item, refs)\n return refs\n }\n\n if (schema && typeof schema === 'object') {\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$ref' && typeof value === 'string') {\n const match = value.match(/^#\\/components\\/schemas\\/(.+)$/)\n if (match) refs.add(match[1]!)\n } else {\n collectRefs(value, refs)\n }\n }\n }\n\n return refs\n}\n\n/**\n * Returns a copy of `schemas` topologically sorted by `$ref` dependency.\n *\n * Schemas with no references come first; schemas that are referenced by others\n * come before those that reference them. This ensures code generators emit\n * referenced types before the types that depend on them.\n *\n * Cycles are silently skipped via the `stack` guard inside `visit`.\n */\nexport function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {\n const deps = new Map<string, string[]>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n deps.set(name, Array.from(collectRefs(schema)))\n }\n\n const sorted: 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\n/**\n * Extracts the inline schema from a media-type `content` map.\n *\n * Prefers `preferredContentType` when provided; otherwise falls back to the\n * first key in the map. Returns `null` when:\n * - `content` is absent.\n * - The target content-type has no `schema` entry.\n * - The schema is a `$ref` (callers resolve refs separately).\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 * Returns the PascalCase suffix appended to a component name when resolving\n * cross-source name collisions (schemas vs. responses vs. requestBodies).\n */\nfunction getSemanticSuffix(source: SchemaSourceMode): string {\n switch (source) {\n case 'schemas':\n return 'Schema'\n case 'responses':\n return 'Response'\n case 'requestBodies':\n return 'Request'\n }\n}\n\n/**\n * Builds `GetSchemasResult` without any collision detection.\n * Each schema is registered under its original component name and its full\n * `#/components/<source>/<name>` ref path.\n */\nexport function legacyResolve(schemasWithMeta: SchemaWithMetadata[]): GetSchemasResult {\n const schemas: Record<string, SchemaObject> = {}\n const nameMapping = new Map<string, string>()\n\n for (const item of schemasWithMeta) {\n schemas[item.originalName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, item.originalName)\n }\n\n return { schemas, nameMapping }\n}\n\n/**\n * Builds `GetSchemasResult` with automatic name-collision resolution.\n *\n * When two or more schemas normalize to the same PascalCase name:\n * - If they share the same source, a numeric suffix (`2`, `3`, …) is appended.\n * - If they come from different sources (schemas / responses / requestBodies),\n * a semantic suffix (`Schema`, `Response`, `Request`) is appended.\n *\n * Non-colliding schemas are left unchanged.\n */\nexport function resolveCollisions(schemasWithMeta: SchemaWithMetadata[]): GetSchemasResult {\n const schemas: Record<string, SchemaObject> = {}\n const nameMapping = new Map<string, string>()\n const normalizedNames = new Map<string, SchemaWithMetadata[]>()\n\n for (const item of schemasWithMeta) {\n const normalized = pascalCase(item.originalName)\n const bucket = normalizedNames.get(normalized) ?? []\n bucket.push(item)\n normalizedNames.set(normalized, bucket)\n }\n\n for (const [, items] of normalizedNames) {\n if (items.length === 1) {\n const item = items[0]!\n schemas[item.originalName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, item.originalName)\n continue\n }\n\n const sources = new Set(items.map((item) => item.source))\n\n if (sources.size === 1) {\n items.forEach((item, index) => {\n const uniqueName = item.originalName + (index === 0 ? '' : (index + 1).toString())\n schemas[uniqueName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n } else {\n items.forEach((item) => {\n const uniqueName = item.originalName + getSemanticSuffix(item.source)\n schemas[uniqueName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n }\n }\n\n return { schemas, nameMapping }\n}\n","import { collect, createProperty, createSchema, narrowSchema } from '@kubb/ast'\nimport type { SchemaNode } from '@kubb/ast/types'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport { SCALAR_PRIMITIVE_TYPES } from './constants.ts'\n\n/**\n * Extracts the schema name from a `$ref` string.\n * For `#/components/schemas/Order` this returns `'Order'`.\n * Falls back to the full ref string when no slash is present.\n */\nexport function extractRefName($ref: string): string {\n return $ref.split('/').at(-1) ?? $ref\n}\n\n/**\n * Replaces the discriminator property's schema inside an `ObjectSchemaNode`\n * with an enum of the given `values`.\n *\n * - When `enumName` is provided the enum is named, which lets printers emit a\n * standalone enum declaration + type reference (e.g. `PetTypeEnum`).\n * - When `enumName` is omitted the enum stays anonymous, so printers inline it\n * as a literal union (e.g. `'dog'`).\n *\n * Returns the node unchanged when it is not an object or lacks the target property.\n */\nexport function applyDiscriminatorEnum({\n node,\n propertyName,\n values,\n enumName,\n}: {\n node: SchemaNode\n propertyName: string\n values: Array<string>\n enumName?: string\n}): SchemaNode {\n if (node.type !== 'object' || !node.properties?.length) return node\n\n const hasProperty = node.properties.some((prop) => prop.name === propertyName)\n if (!hasProperty) return node\n\n return createSchema({\n ...node,\n properties: node.properties.map((prop) => {\n if (prop.name !== propertyName) return prop\n\n const enumSchema: SchemaNode = createSchema({\n type: 'enum' as const,\n primitive: 'string' as const,\n enumValues: values,\n name: enumName,\n readOnly: prop.schema.readOnly,\n writeOnly: prop.schema.writeOnly,\n })\n\n return createProperty({\n ...prop,\n schema: enumSchema,\n })\n }),\n })\n}\n\n/**\n * Merges consecutive anonymous (`name`-less) `ObjectSchemaNode`s in `members` into a\n * single object by combining their `properties` arrays.\n *\n * Only adjacent pairs are merged — non-object or named nodes act as boundaries.\n * This collapses patterns like `Address & { streetNumber } & { streetName }` into\n * `Address & { streetNumber; streetName }`.\n */\nexport function mergeAdjacentAnonymousObjects(members: Array<SchemaNode>): Array<SchemaNode> {\n return members.reduce<Array<SchemaNode>>((acc, member) => {\n const obj = narrowSchema(member, 'object')\n if (obj && !obj.name) {\n const prev = acc[acc.length - 1]\n const prevObj = prev ? narrowSchema(prev, 'object') : null\n if (prevObj && !prevObj.name) {\n acc[acc.length - 1] = createSchema({\n ...prevObj,\n properties: [...(prevObj.properties ?? []), ...(obj.properties ?? [])],\n }) as SchemaNode\n return acc\n }\n }\n acc.push(member)\n return acc\n }, [])\n}\n\n/**\n * Simplifies a union member list by removing `enum` nodes whose `primitive` type is\n * already represented by a broader scalar node in the same union.\n *\n * For example `['placed', 'approved'] | string` collapses to `string` because\n * `string` subsumes all string literals. `'' | string` similarly becomes `string`.\n *\n * Only scalar primitives (`string`, `number`, `integer`, `bigint`, `boolean`) are\n * considered — object, array, and ref members are left untouched.\n *\n * Const-derived enums (those without an `enumType`, produced from an OpenAPI `const`\n * keyword) are **never** removed — `'accepted' | string` must stay as-is because the\n * literal is intentional.\n */\nexport function simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {\n const scalarPrimitives = new Set(members.filter((m) => SCALAR_PRIMITIVE_TYPES.has(m.type as 'string')).map((m) => m.type as string))\n if (!scalarPrimitives.size) return members\n\n return members.filter((m) => {\n if (m.type !== 'enum') return true\n const prim = m.primitive\n // Keep the enum if its primitive isn't fully subsumed.\n if (!prim) return true\n // Const-derived enums have no `enumType`; keep them as intentional literals.\n if (!m.enumType) return true\n // `number` subsumes `integer` literals and vice-versa for our purposes.\n if (scalarPrimitives.has(prim)) return false\n if ((prim === 'integer' || prim === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false\n return true\n })\n}\n\n/**\n * `nameMapping`, and calls `resolve` to obtain the `{ name, path }` pair for\n * each import. When `oas` is supplied, only `$ref`s that are resolvable in the\n * spec are included; omit it to skip the existence check.\n *\n * This function is the pure, state-free alternative to `OasParser.getImports`.\n * Because it receives `nameMapping` explicitly it can be called without holding\n * a reference to the parser or the OAS instance.\n *\n * @example\n * ```ts\n * // Use adapter state directly — no parser reference needed\n * const imports = getImports({\n * node: schemaNode,\n * nameMapping: adapter.options.nameMapping,\n * resolve: (schemaName) => ({\n * name: schemaManager.getName(schemaName, { type: 'type' }),\n * path: schemaManager.getFile(schemaName).path,\n * }),\n * })\n * ```\n */\nexport function getImports({\n node,\n nameMapping,\n resolve,\n}: {\n node: SchemaNode\n nameMapping: Map<string, string>\n resolve: (schemaName: string) => { name: string; path: string } | undefined\n}): Array<KubbFile.Import> {\n return collect<KubbFile.Import>(node, {\n schema(schemaNode): KubbFile.Import | undefined {\n if (schemaNode.type !== 'ref' || !schemaNode.ref) return\n\n const rawName = extractRefName(schemaNode.ref)\n\n // Apply collision-resolved name if available.\n const schemaName = nameMapping.get(rawName) ?? rawName\n const result = resolve(schemaName)\n if (!result) return\n\n return { name: [result.name], path: result.path }\n },\n })\n}\n","import { getUniqueName, pascalCase, URLPath } from '@internals/utils'\nimport { createOperation, createParameter, createProperty, createResponse, createRoot, createSchema, narrowSchema, schemaTypes, transform } from '@kubb/ast'\nimport type {\n ArraySchemaNode,\n DateSchemaNode,\n DatetimeSchemaNode,\n EnumSchemaNode,\n HttpMethod,\n IntersectionSchemaNode,\n MediaType,\n NumberSchemaNode,\n ObjectSchemaNode,\n OperationNode,\n ParameterLocation,\n ParameterNode,\n PrimitiveSchemaType,\n PropertyNode,\n RefSchemaNode,\n ResponseNode,\n RootNode,\n ScalarSchemaNode,\n ScalarSchemaType,\n SchemaNode,\n SchemaType,\n StatusCode,\n StringSchemaNode,\n TimeSchemaNode,\n UnionSchemaNode,\n} from '@kubb/ast/types'\nimport { DEFAULT_PARSER_OPTIONS, enumExtensionKeys, formatMap, knownMediaTypes } from './constants.ts'\nimport type { Oas } from './oas/Oas.ts'\nimport type { contentType, Operation, ReferenceObject, SchemaObject } from './oas/types.ts'\nimport { flattenSchema, isDiscriminator, isNullable, isReference } from './oas/utils.ts'\nimport type { ParserOptions } from './types.ts'\nimport { applyDiscriminatorEnum, extractRefName, mergeAdjacentAnonymousObjects, simplifyUnionMembers } from './utils.ts'\n\n/**\n * Distributive `Omit` — correctly distributes over union types so that\n * `Omit<A | B, 'kind'>` produces `Omit<A, 'kind'> | Omit<B, 'kind'>`\n * rather than `Omit<A | B, 'kind'>`.\n */\ntype DistributiveOmit<TValue, TKey extends PropertyKey> = TValue extends unknown ? Omit<TValue, TKey> : never\n\n/**\n * Maps each `dateType` option value to the AST node produced by `format: 'date-time'`.\n */\ntype DateTimeNodeByDateType = {\n date: DateSchemaNode\n string: DatetimeSchemaNode\n stringOffset: DatetimeSchemaNode\n stringLocal: DatetimeSchemaNode\n false: StringSchemaNode\n}\n\n/**\n * Resolves the AST node produced by `format: 'date-time'` based on the `dateType` option.\n */\ntype ResolveDateTimeNode<TDateType extends ParserOptions['dateType']> = DateTimeNodeByDateType[TDateType extends keyof DateTimeNodeByDateType\n ? TDateType\n : 'string']\n\n/**\n * Single source of truth: ordered list of `[shape, SchemaNode]` pairs.\n * `InferSchemaNode` walks this tuple in order and returns the node type of the first matching entry.\n * Parameterized over `TDateType` so `format: 'date-time'` resolves to the correct node based on the option.\n */\ntype SchemaNodeMap<TDateType extends ParserOptions['dateType'] = 'string'> = [\n [{ $ref: string }, RefSchemaNode],\n // allOf with sibling `properties` always produces an intersection (shared props are appended as a member).\n [{ allOf: ReadonlyArray<unknown>; properties: object }, IntersectionSchemaNode],\n // allOf with 2+ members always produces an intersection.\n [{ allOf: readonly [unknown, unknown, ...unknown[]] }, IntersectionSchemaNode],\n // Single-member allOf without sibling `properties` flattens to the member type.\n [{ allOf: ReadonlyArray<unknown> }, SchemaNode],\n [{ oneOf: ReadonlyArray<unknown> }, UnionSchemaNode],\n [{ anyOf: ReadonlyArray<unknown> }, UnionSchemaNode],\n [{ const: null }, ScalarSchemaNode],\n [{ const: string | number | boolean }, EnumSchemaNode],\n // OAS 3.1 multi-type array: `{ type: ['string', 'integer'] }` → union node.\n [{ type: ReadonlyArray<string> }, UnionSchemaNode],\n // `{ type: 'array', enum }` is normalized at runtime: enum moves into items → array node.\n [{ type: 'array'; enum: ReadonlyArray<unknown> }, ArraySchemaNode],\n [{ enum: ReadonlyArray<unknown> }, EnumSchemaNode],\n [{ type: 'object' }, ObjectSchemaNode],\n [{ additionalProperties: boolean | {} }, ObjectSchemaNode],\n [{ type: 'array' }, ArraySchemaNode],\n [{ items: object }, ArraySchemaNode],\n [{ prefixItems: ReadonlyArray<unknown> }, ArraySchemaNode],\n // Format entries with explicit type — placed before generic type entries so format wins.\n [{ type: string; format: 'date-time' }, ResolveDateTimeNode<TDateType>],\n [{ type: string; format: 'date' }, DateSchemaNode],\n [{ type: string; format: 'time' }, TimeSchemaNode],\n [{ format: 'date-time' }, ResolveDateTimeNode<TDateType>],\n [{ format: 'date' }, DateSchemaNode],\n [{ format: 'time' }, TimeSchemaNode],\n [{ type: 'string' }, StringSchemaNode],\n [{ type: 'number' }, NumberSchemaNode],\n [{ type: 'integer' }, NumberSchemaNode],\n [{ type: 'bigint' }, NumberSchemaNode],\n [{ type: string }, ScalarSchemaNode],\n // Inferred scalar types from constraints when no explicit type is present.\n [{ minLength: number }, StringSchemaNode],\n [{ maxLength: number }, StringSchemaNode],\n [{ pattern: string }, StringSchemaNode],\n [{ minimum: number }, NumberSchemaNode],\n [{ maximum: number }, NumberSchemaNode],\n]\n\nexport type InferSchemaNode<\n TSchema extends SchemaObject,\n TDateType extends ParserOptions['dateType'] = 'string',\n TEntries extends ReadonlyArray<[object, SchemaNode]> = SchemaNodeMap<TDateType>,\n> = TEntries extends [infer TEntry extends [object, SchemaNode], ...infer TRest extends ReadonlyArray<[object, SchemaNode]>]\n ? TSchema extends TEntry[0]\n ? TEntry[1]\n : InferSchemaNode<TSchema, TDateType, TRest>\n : SchemaNode\n\n/**\n * Construction-time options for `createOasParser`.\n */\nexport type OasParserOptions = {\n contentType?: contentType\n collisionDetection?: boolean\n}\n\n/**\n * Looks up the Kubb `SchemaType` for a given OAS `format` string.\n * Returns `undefined` for formats not in `formatMap` (e.g. `int64`, `date-time`),\n * which are handled separately because their output depends on parser options.\n */\nfunction formatToSchemaType(format: string): SchemaType | undefined {\n return formatMap[format as keyof typeof formatMap]\n}\n\n/**\n * Maps an OAS primitive type string to its `PrimitiveSchemaType` equivalent.\n * Numeric types (`number`, `integer`, `bigint`) are returned unchanged;\n * `boolean` maps to `'boolean'`; everything else defaults to `'string'`.\n */\nfunction getPrimitiveType(type: string | undefined): PrimitiveSchemaType {\n if (type === 'number' || type === 'integer' || type === 'bigint') return type\n if (type === 'boolean') return 'boolean'\n return 'string'\n}\n\n/**\n * Narrows a raw content-type string to the `MediaType` union recognized by Kubb.\n * Returns `undefined` for content types not present in `KNOWN_MEDIA_TYPES`.\n */\nfunction toMediaType(contentType: string): MediaType | undefined {\n return knownMediaTypes.has(contentType as MediaType) ? (contentType as MediaType) : undefined\n}\n\n/**\n * Pre-computed per-schema context passed to every `convert*` branch handler.\n * Grouping these values avoids repeating the same derivations across all branches.\n */\ntype SchemaContext = {\n schema: SchemaObject\n name: string | 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 options: Partial<ParserOptions> | undefined\n mergedOptions: ParserOptions\n}\n\n/**\n * The public interface returned by `createOasParser`.\n */\nexport type OasParser = {\n /**\n * Converts an OpenAPI/Swagger spec (wrapped in a Kubb `Oas` instance) into\n * a `RootNode` — the top-level node of the `@kubb/ast` tree.\n */\n parse: <TOptions extends Partial<ParserOptions> = object>(options?: TOptions) => RootNode\n convertSchema: <TFormat extends string, TSchema extends SchemaObject & { format?: TFormat }, TOptions extends Partial<ParserOptions> = object>(\n params: { schema: TSchema; name?: string },\n options?: TOptions,\n ) => InferSchemaNode<TSchema, TOptions extends { dateType: ParserOptions['dateType'] } ? TOptions['dateType'] : 'string'>\n /**\n * Walks `node` and replaces each `ref` value with the name returned by\n * `resolveName`. The callback receives the full `$ref` path (e.g. `#/components/schemas/Order`)\n * when available, falling back to the short name. Pass a no-op (`(n) => n`) to skip resolution.\n *\n * The optional `resolveEnumName` callback is called for inline `enum` nodes and should return\n * the transformed name to use (e.g. with a plugin `transformers.name` applied).\n */\n resolveRefs: (node: SchemaNode, resolveName: (ref: string) => string | undefined, resolveEnumName?: (name: string) => string | undefined) => SchemaNode\n\n /**\n * Map from original `$ref` paths to their collision-resolved schema names.\n * e.g. `'#/components/schemas/Order'` → `'OrderSchema'`\n *\n * Pass this to the standalone `getImports()` to resolve imports without holding\n * a reference to the full parser or OAS instance.\n */\n nameMapping: Map<string, string>\n}\n\n/**\n * Creates an OAS parser that converts an OpenAPI/Swagger spec into\n * the `@kubb/ast` tree.\n *\n * Options are passed per-call to `parse` or `convertSchema` rather than\n * at construction time, keeping the factory lightweight.\n *\n * This is the **kubb-parser** stage of the compilation lifecycle:\n * OpenAPI / Swagger → Kubb AST\n *\n * No code is generated here; the resulting tree is spec-agnostic and can\n * be consumed by any downstream plugin (plugin-ts, plugin-zod, …).\n *\n * @example\n * ```ts\n * const parser = createOasParser(oas)\n * const root = parser.parse({ emptySchemaType: 'unknown' })\n * ```\n */\nexport function createOasParser(oas: Oas, { contentType, collisionDetection }: OasParserOptions = {}): OasParser {\n // Map from original component paths to resolved schema names (after collision resolution)\n // e.g., { '#/components/schemas/Order': 'OrderSchema', '#/components/responses/Product': 'ProductResponse' }\n const { schemas: schemaObjects, nameMapping } = oas.getSchemas({ contentType, collisionDetection })\n\n // Legacy enum name deduplication: tracks used enum names and appends numeric suffixes\n // (e.g. ParamsStatusEnum, ParamsStatusEnum2) when collisionDetection is disabled.\n const usedEnumNames: Record<string, number> = {}\n\n // Only apply legacy naming when collisionDetection is explicitly false.\n // When undefined (e.g. direct parser usage without adapter), use the default (new) behavior.\n const isLegacyNaming = collisionDetection === false\n\n /**\n * Maps an `'any' | 'unknown' | 'void'` option string to the corresponding `SchemaType` constant.\n * Used for both `unknownType` (unannotated schemas) and `emptySchemaType` (empty `{}` schemas).\n */\n function resolveTypeOption(value: 'any' | 'unknown' | 'void'): ScalarSchemaType {\n if (value === 'any') return schemaTypes.any\n if (value === 'void') return schemaTypes.void\n return schemaTypes.unknown\n }\n\n /**\n * Resolves the AST type and datetime modifiers for a date/time format, honoring the `dateType` option.\n * Returns `undefined` when `dateType` is `false`, meaning the format should fall through to `string`.\n */\n function getDateType(\n options: ParserOptions,\n format: 'date-time' | 'date' | 'time',\n ): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | undefined {\n if (!options.dateType) {\n return undefined\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 { type: 'date', representation: options.dateType === 'date' ? 'date' : 'string' }\n }\n\n // time\n return { type: 'time', representation: options.dateType === 'date' ? 'date' : 'string' }\n }\n\n /**\n * Shared metadata fields included in every `createSchema` call.\n * Centralizes the common properties so sub-handlers don't repeat them.\n */\n function renderSchemaBase(schema: SchemaObject, name: string | 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 } as const\n }\n\n // Branch handlers — each converts one OAS schema pattern to a SchemaNode.\n // They are defined as function declarations so they can reference each other\n // and `convertSchema` freely (JS hoisting).\n\n /**\n * Converts a `$ref` schema pointer into a `RefSchemaNode`.\n *\n * In OAS 3.0 siblings of `$ref` are technically ignored by the spec, but Kubb intentionally\n * preserves them so that annotations like `pattern`, `description`, and `nullable` are\n * reflected in generated JSDoc and type modifiers.\n */\n function convertRef({ schema, nullable, defaultValue }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'ref',\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n nullable,\n description: schema.description,\n deprecated: schema.deprecated,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n pattern: schema.type === 'string' ? schema.pattern : undefined,\n example: schema.example,\n default: defaultValue,\n })\n }\n\n /**\n * Converts a `allOf` schema into either a flattened member node (single-member `allOf`)\n * or an `IntersectionSchemaNode` (multi-member `allOf`).\n *\n * Single-member `allOf` without sibling structural keys is the common OAS 3.0 pattern for\n * annotating a `$ref` or primitive with extra constraints; it is flattened to avoid\n * producing needless intersection wrappers.\n *\n * The flatten path is skipped when the outer schema carries structural keys that cannot be\n * merged into annotation fields: `properties`, `required`, or `additionalProperties`.\n * Those cases must become an intersection so the constraints are preserved.\n *\n * Circular references through discriminator parents are detected and skipped to prevent\n * infinite recursion during code generation.\n */\n function convertAllOf({ schema, name, nullable, defaultValue, options }: SchemaContext): 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 = convertSchema({ schema: memberSchema! as SchemaObject }, options)\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 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 } as DistributiveOmit<SchemaNode, 'kind'>)\n }\n\n // When a child schema extends a discriminator parent via allOf and the parent's oneOf/anyOf\n // references that child back, skip that allOf item to prevent a circular type reference.\n // When an item is skipped, collect its discriminant value so it can be injected below.\n const filteredDiscriminantValues: Array<{ propertyName: string; value: string }> = []\n const allOfMembers: Array<SchemaNode> = (schema.allOf as Array<SchemaObject | ReferenceObject>)\n .filter((item) => {\n if (!isReference(item) || !name) return true\n const deref = oas.get<SchemaObject>(item.$ref)\n if (!deref || !isDiscriminator(deref)) return true\n const parentUnion = deref.oneOf ?? deref.anyOf\n if (!parentUnion) return true\n const childRef = `#/components/schemas/${name}`\n const inOneOf = parentUnion.some((oneOfItem) => isReference(oneOfItem) && oneOfItem.$ref === childRef)\n const inMapping = Object.values(deref.discriminator.mapping ?? {}).some((v) => v === childRef)\n if (inOneOf || inMapping) {\n const discriminatorValue = Object.entries(deref.discriminator.mapping ?? {}).find(([, v]) => v === childRef)?.[0]\n if (discriminatorValue) {\n filteredDiscriminantValues.push({ propertyName: deref.discriminator.propertyName, value: discriminatorValue })\n }\n return false\n }\n return true\n })\n .map((s) => convertSchema({ schema: s as SchemaObject }, options))\n\n // Track where allOf-derived members end so each portion can be merged independently.\n const syntheticStart = allOfMembers.length\n\n // When `required` lists keys not present in the outer `properties`, resolve them from\n // the allOf member schemas and inject them as extra intersection members.\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 (!isReference(item)) return [item as SchemaObject]\n const deref = oas.get<SchemaObject>(item.$ref)\n return deref && !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(convertSchema({ schema: { properties: { [key]: resolved.properties[key] }, required: [key] } as SchemaObject }, options))\n break\n }\n }\n }\n }\n }\n\n if (schema.properties) {\n const { allOf: _allOf, ...schemaWithoutAllOf } = schema\n allOfMembers.push(convertSchema({ schema: schemaWithoutAllOf }, options))\n }\n\n // Inject a synthetic single-property object for each discriminant value collected from\n // filtered discriminator parents so that child schemas carry the narrowed literal type.\n for (const { propertyName, value } of filteredDiscriminantValues) {\n allOfMembers.push(\n createSchema({\n type: 'object',\n primitive: 'object',\n properties: [\n createProperty({\n name: propertyName,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: [value],\n }),\n required: true,\n }),\n ],\n }),\n )\n }\n\n // Merge consecutive anonymous object members within the synthetic portion — see `mergeAdjacentAnonymousObjects`.\n return createSchema({\n type: 'intersection',\n members: [...mergeAdjacentAnonymousObjects(allOfMembers.slice(0, syntheticStart)), ...mergeAdjacentAnonymousObjects(allOfMembers.slice(syntheticStart))],\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n *\n * Both keywords are treated identically — their members are concatenated into a single union.\n * When sibling `properties` are present alongside `oneOf`/`anyOf`, each union member is\n * individually intersected with the shared properties node to match the OAS pattern of\n * adding common fields next to a discriminated union.\n */\n function convertUnion({ schema, name, nullable, defaultValue, options }: SchemaContext): SchemaNode {\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n const unionBase = {\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n discriminatorPropertyName: isDiscriminator(schema) ? schema.discriminator.propertyName : undefined,\n }\n\n if (schema.properties) {\n const { oneOf: _oneOf, anyOf: _anyOf, ...schemaWithoutUnion } = schema\n const discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n\n // Strip discriminator so convertObject won't re-apply the full mapping enum.\n const memberBaseSchema: SchemaObject = discriminator\n ? (Object.fromEntries(Object.entries(schemaWithoutUnion).filter(([key]) => key !== 'discriminator')) as SchemaObject)\n : schemaWithoutUnion\n\n // Convert shared properties once to avoid duplicate enum naming\n // (e.g. StatusEnum appearing twice and getting a numeric suffix).\n const sharedPropertiesNode = convertSchema({ schema: memberBaseSchema, name: isLegacyNaming ? undefined : name }, options)\n\n return createSchema({\n type: 'union',\n ...unionBase,\n members: unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n const discriminatorValue = discriminator?.mapping && ref ? Object.entries(discriminator.mapping).find(([, v]) => v === ref)?.[0] : undefined\n\n let propertiesNode = sharedPropertiesNode\n\n if (discriminatorValue && discriminator) {\n propertiesNode = applyDiscriminatorEnum({ node: propertiesNode, propertyName: discriminator.propertyName, values: [discriminatorValue] })\n }\n\n return createSchema({\n type: 'intersection',\n members: [convertSchema({ schema: s as SchemaObject }, options), propertiesNode],\n })\n }),\n })\n }\n\n // When a discriminator with mapping is present but there are no sibling properties,\n // embed the narrowed discriminant value into each member to produce precise literal\n // intersection types (e.g. `Cat & { type: 'cat' }`) instead of plain `Cat | Dog`.\n const discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n if (discriminator?.mapping) {\n return createSchema({\n type: 'union',\n ...unionBase,\n members: unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n const discriminatorValue = ref ? Object.entries(discriminator.mapping!).find(([, v]) => v === ref)?.[0] : undefined\n const memberNode = convertSchema({ schema: s as SchemaObject }, options)\n\n if (!discriminatorValue) return memberNode\n\n const discriminantNode = createSchema({\n type: 'object',\n primitive: 'object',\n properties: [\n createProperty({\n name: discriminator.propertyName,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: [discriminatorValue],\n }),\n required: true,\n }),\n ],\n })\n\n return createSchema({\n type: 'intersection',\n members: [memberNode, discriminantNode],\n })\n }),\n })\n }\n\n return createSchema({\n type: 'union',\n ...unionBase,\n members: simplifyUnionMembers(unionMembers.map((s) => convertSchema({ schema: s as SchemaObject }, options))),\n })\n }\n\n /**\n * Converts an OAS 3.1 `const` schema into either a null scalar or a single-value `EnumSchemaNode`.\n * `const: null` maps to a null scalar; any other value becomes a one-item enum so that generators\n * can produce a precise literal type.\n */\n function convertConst({ schema, name, nullable, defaultValue }: SchemaContext): SchemaNode {\n const constValue = schema.const\n\n if (constValue === null) {\n // Do not propagate `nullable` here: the type is already `null`, so marking it\n // nullable too would cause the printer to emit `null | null`.\n return createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n })\n }\n\n const constPrimitive = getPrimitiveType(typeof constValue === 'number' ? 'number' : typeof constValue === 'boolean' ? 'boolean' : 'string')\n return createSchema({\n type: 'enum',\n primitive: constPrimitive,\n enumValues: [constValue as string | number | boolean],\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Handles `format`-based special types (date/time, uuid, email, blob, etc.).\n * Returns `undefined` when the format should fall through to string handling\n * (i.e. `format: 'date-time'` with `dateType: false`).\n */\n function convertFormat({ schema, name, nullable, defaultValue, mergedOptions }: SchemaContext): SchemaNode | undefined {\n const base = renderSchemaBase(schema, name, nullable, defaultValue)\n\n // int64 is option-dependent so it can't live in the static formatMap.\n if (schema.format === 'int64') {\n return createSchema({\n type: mergedOptions.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 // date-time / date / time are option-dependent and can't live in the static formatMap.\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const dateType = getDateType(mergedOptions, schema.format)\n if (!dateType) return undefined // dateType: false → fall through to string\n\n if (dateType.type === 'datetime') {\n return createSchema({ ...base, primitive: 'string' as const, type: 'datetime', offset: dateType.offset, local: dateType.local })\n }\n return createSchema({ ...base, primitive: 'string' as const, type: dateType.type, representation: dateType.representation })\n }\n\n const specialType = formatToSchemaType(schema.format!)\n if (!specialType) return undefined\n\n const specialPrimitive: PrimitiveSchemaType = specialType === 'number' || specialType === 'integer' || specialType === 'bigint' ? specialType : 'string'\n\n if (specialType === 'number' || specialType === 'integer' || specialType === 'bigint') {\n return createSchema({ ...base, primitive: specialPrimitive, type: specialType })\n }\n if (specialType === 'url') {\n return createSchema({ ...base, primitive: 'string' as const, type: 'url' })\n }\n\n return createSchema({ ...base, primitive: specialPrimitive, type: specialType as ScalarSchemaType })\n }\n\n /**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n *\n * Handles several edge cases:\n * - `{ type: 'array', enum }` (technically invalid OAS) — the enum is normalized into `items`.\n * - `null` in enum values (OAS 3.0 nullable enum convention) — stripped and reflected as `nullable`.\n * - `x-enumNames` / `x-enum-varnames` vendor extensions — produce named enum variants with explicit labels.\n * - Numeric and boolean enums require a const-map representation because most generators cannot\n * use string-enum syntax for non-string values.\n */\n function convertEnum({ schema, name, nullable, type, options }: SchemaContext): SchemaNode {\n // Malformed schema: `{ type: 'array', enum: [...] }` — normalize by moving the enum into items.\n if (type === 'array') {\n const isItemsObject = typeof schema.items === 'object' && !Array.isArray(schema.items)\n const normalizedItems: SchemaObject = { ...(isItemsObject ? (schema.items as SchemaObject) : {}), enum: schema.enum }\n const { enum: _enum, ...schemaWithoutEnum } = schema\n return convertSchema({ schema: { ...schemaWithoutEnum, items: normalizedItems } as SchemaObject, name }, options)\n }\n\n // `null` in enum values is the OAS 3.0 convention for a nullable enum.\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 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 }\n\n // x-enumNames / x-enum-varnames: named variants with explicit labels take priority.\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n if (extensionKey) {\n const rawNames = (schema as Record<string, unknown>)[extensionKey] as Array<string | number>\n const uniqueNames = [...new Set(rawNames)]\n const enumType =\n getPrimitiveType(type) === 'number' || getPrimitiveType(type) === 'integer'\n ? ('number' as const)\n : getPrimitiveType(type) === 'boolean'\n ? ('boolean' as const)\n : ('string' as const)\n\n return createSchema({\n ...enumBase,\n enumType,\n namedEnumValues: uniqueNames.map((label, index) => ({\n name: String(label),\n value: filteredValues[index] ?? label,\n format: enumType,\n })),\n })\n }\n\n // Number / integer enum — must use a const map since most generators can't use string-enum for numbers.\n if (type === 'number' || type === 'integer') {\n return createSchema({\n ...enumBase,\n enumType: 'number' as const,\n namedEnumValues: [...new Set(filteredValues)].map((value) => ({\n name: String(value),\n value: value as number,\n format: 'number' as const,\n })),\n })\n }\n\n // Boolean enum — same const-map approach as numeric.\n if (type === 'boolean') {\n return createSchema({\n ...enumBase,\n enumType: 'boolean' as const,\n namedEnumValues: [...new Set(filteredValues)].map((value) => ({\n name: String(value),\n value: value as boolean,\n format: 'boolean' as const,\n })),\n })\n }\n\n // Plain string enum (default path).\n return createSchema({\n ...enumBase,\n enumValues: [...new Set(filteredValues)],\n })\n }\n\n /**\n * Converts an object-like schema (`type: 'object'`, `properties`, `additionalProperties`,\n * or `patternProperties`) into an `ObjectSchemaNode`.\n *\n * When a `discriminator` is present, the discriminator property's schema is replaced with an\n * enum of the mapping keys so generators can produce a precise literal-union type for it.\n *\n * Property optionality follows OAS semantics:\n * - required + not nullable → `required: true`\n * - not required + not nullable → `optional: true`\n * - not required + nullable → `nullish: true`\n */\n /**\n * Builds the propagation name for a child property during recursive schema conversion.\n *\n * - **Legacy naming** (`isLegacyNaming`): only the immediate property key is used\n * (e.g. `Params` for property `params`), keeping nested names short.\n * - **Default naming**: the parent name is prepended so the full path is encoded\n * (e.g. `OrderParams` when parent is `Order`).\n */\n function resolveChildName(parentName: string | undefined, propName: string): string | undefined {\n if (isLegacyNaming) {\n return pascalCase(propName)\n }\n return parentName ? pascalCase([parentName, propName].join(' ')) : undefined\n }\n\n /**\n * Derives the final name for an enum property schema node.\n *\n * The raw name always includes the enum suffix (e.g. `StatusEnum`).\n * In legacy mode an additional deduplication step appends a numeric suffix\n * when the same name has already been used (e.g. `ParamsStatusEnum2`).\n */\n function resolveEnumPropName(parentName: string | undefined, propName: string, enumSuffix: string): string {\n const raw = pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))\n return isLegacyNaming ? getUniqueName(raw, usedEnumNames) : raw\n }\n\n /**\n * Given a freshly-converted property schema, returns the node with a correct\n * `name` attached — or stripped — depending on whether the node is a named\n * enum, a boolean const-enum (always inlined), or a regular schema.\n */\n function applyEnumName(propNode: SchemaNode, parentName: string | undefined, propName: string, enumSuffix: string): SchemaNode {\n const enumNode = narrowSchema(propNode, 'enum')\n\n // Boolean-primitive enum nodes (e.g. `const: false`) are always inlined as\n // literal types and must not receive a named identifier.\n if (enumNode?.primitive === 'boolean') {\n return { ...propNode, name: undefined }\n }\n\n if (enumNode) {\n return { ...propNode, name: resolveEnumPropName(parentName, propName, enumSuffix) }\n }\n\n return propNode\n }\n\n function convertObject({ schema, name, nullable, defaultValue, options, mergedOptions }: SchemaContext): SchemaNode {\n const properties: Array<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 = isNullable(resolvedPropSchema)\n\n const childName = resolveChildName(name, propName)\n const propNode = convertSchema({ schema: resolvedPropSchema, name: childName }, options)\n let schemaNode = applyEnumName(propNode, name, propName, mergedOptions.enumSuffix)\n\n const tupleNode = narrowSchema(schemaNode, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => applyEnumName(item, name, propName, mergedOptions.enumSuffix))\n if (namedItems.some((item, i) => item !== tupleNode.items![i])) {\n schemaNode = { ...tupleNode, items: namedItems }\n }\n }\n\n return createProperty({\n name: propName,\n schema: {\n ...schemaNode,\n nullable: schemaNode.type === 'null' ? undefined : propNullable || undefined,\n optional: !required && !propNullable ? true : undefined,\n nullish: !required && propNullable ? true : undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n let additionalPropertiesNode: SchemaNode | true | undefined\n if (additionalProperties === true) {\n additionalPropertiesNode = true\n } else if (additionalProperties && Object.keys(additionalProperties).length > 0) {\n additionalPropertiesNode = convertSchema({ schema: additionalProperties as SchemaObject }, options)\n } else if (additionalProperties === false) {\n additionalPropertiesNode = undefined\n } else if (additionalProperties) {\n additionalPropertiesNode = createSchema({ type: resolveTypeOption(mergedOptions.unknownType) })\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 ? createSchema({ type: resolveTypeOption(mergedOptions.unknownType) })\n : convertSchema({ schema: patternSchema as SchemaObject }, options),\n ]),\n )\n : undefined\n\n const objectNode: SchemaNode = createSchema({\n type: 'object',\n primitive: 'object',\n properties,\n additionalProperties: additionalPropertiesNode,\n patternProperties,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n\n // When a discriminator is present, replace the discriminator property's schema\n // with an enum of the mapping keys for a precise literal-union type.\n if (isDiscriminator(schema) && schema.discriminator.mapping) {\n const discPropName = schema.discriminator.propertyName\n const values = Object.keys(schema.discriminator.mapping)\n const enumName = name ? resolveEnumPropName(name, discPropName, mergedOptions.enumSuffix) : undefined\n return applyDiscriminatorEnum({ node: objectNode, propertyName: discPropName, values, enumName })\n }\n\n return objectNode\n }\n\n /**\n * Converts an OAS 3.1 `prefixItems` tuple into a `TupleSchemaNode`.\n *\n * Each `prefixItems` element maps to a positional tuple slot. When an explicit `items` schema\n * is present alongside `prefixItems`, it becomes the rest element. When `items` is absent,\n * a rest element of type `any` is emitted to match JSON Schema semantics (absent `items`\n * means additional items are allowed).\n */\n function convertTuple({ schema, name, nullable, defaultValue, options }: SchemaContext): SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => convertSchema({ schema: item as SchemaObject }, options))\n const rest = schema.items ? convertSchema({ schema: schema.items as SchemaObject }, options) : createSchema({ type: 'any' })\n\n return createSchema({\n type: 'tuple',\n primitive: 'array',\n items: tupleItems,\n rest,\n min: schema.minItems,\n max: schema.maxItems,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'array'` schema into an `ArraySchemaNode`.\n *\n * When the items schema is an inline enum, a name derived from the parent array's name and\n * `enumSuffix` is forwarded so generators can emit a named enum declaration.\n */\n function convertArray({ schema, name, nullable, defaultValue, options, mergedOptions }: SchemaContext): SchemaNode {\n const rawItems = schema.items as SchemaObject | undefined\n // When the items schema contains an inline enum, derive a named identifier\n // so generators can emit a standalone enum declaration.\n const itemName = rawItems?.enum?.length && name ? resolveEnumPropName(undefined, name, mergedOptions.enumSuffix) : undefined\n const items = rawItems ? [convertSchema({ schema: rawItems, name: itemName }, options)] : []\n\n return createSchema({\n type: 'array',\n primitive: 'array',\n items,\n min: schema.minItems,\n max: schema.maxItems,\n unique: schema.uniqueItems ?? undefined,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'string'` schema (without a special format) into a `StringSchemaNode`.\n */\n function convertString({ schema, name, nullable, defaultValue }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'number'` or `type: 'integer'` schema into the corresponding `SchemaNode`.\n */\n function convertNumeric({ schema, name, nullable, defaultValue }: SchemaContext, type: 'number' | 'integer'): SchemaNode {\n return 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 ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'boolean'` schema into a `BooleanSchemaNode`.\n */\n function convertBoolean({ schema, name, nullable, defaultValue }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'boolean',\n primitive: 'boolean',\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts an explicit `type: 'null'` or `const: null` schema into a `NullSchemaNode`.\n */\n function convertNull({ schema, name, nullable }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable,\n })\n }\n\n /**\n * Central dispatcher: converts an OAS `SchemaObject` into a `SchemaNode`.\n *\n * Dispatch order (first match wins):\n * 1. `$ref` pointer\n * 2. `allOf` composition\n * 3. `oneOf` / `anyOf` union\n * 4. `const` literal (OAS 3.1)\n * 5. `format`-based special type (date/time, uuid, blob, …)\n * 6. OAS 3.1 `contentMediaType: 'application/octet-stream'` blob\n * 7. OAS 3.1 multi-type array → union or fallthrough\n * 8. Constraint-inferred type (minLength/maxLength → string; minimum/maximum → number)\n * 9. `enum` values\n * 10. Object / array / tuple / scalar by `type`\n * 11. Empty schema fallback (`emptySchemaType` option)\n */\n function convertSchema({ schema, name }: { schema: SchemaObject; name?: string }, options?: Partial<ParserOptions>): SchemaNode {\n const mergedOptions: ParserOptions = { ...DEFAULT_PARSER_OPTIONS, ...options }\n // Flatten keyword-only allOf fragments (no $ref, no structural keys) into the parent\n // schema before parsing, so simple annotation patterns don't produce needless intersections.\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema && flattenedSchema !== schema) {\n return convertSchema({ schema: flattenedSchema, name }, options)\n }\n\n const nullable = isNullable(schema) || undefined\n const defaultValue = schema.default === null && nullable ? undefined : schema.default\n // Normalize OAS 3.1 multi-type array to a single type string for the dispatch below.\n const type = Array.isArray(schema.type) ? schema.type[0] : schema.type\n\n const ctx: SchemaContext = { schema, name, nullable, defaultValue, type, options, mergedOptions }\n\n // $ref — pointer to another definition.\n // In OAS 3.0 siblings of $ref are technically ignored, but Kubb intentionally preserves them\n // so that annotations like `pattern`, `description`, and `nullable` are reflected in generated code.\n if (isReference(schema)) return convertRef(ctx)\n\n // Composition keywords\n if (schema.allOf?.length) return convertAllOf(ctx)\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n if (unionMembers.length) return convertUnion(ctx)\n\n // OAS 3.1 const — a single fixed value, semantically equivalent to a one-item enum.\n // `const: undefined` falls through to the empty-type fallback.\n if ('const' in schema && schema.const !== undefined) return convertConst(ctx)\n\n // Format-based special types take precedence over `type`.\n // `convertFormat` returns undefined when format should fall through to string (dateType: false).\n // see https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7\n if (schema.format) {\n const formatResult = convertFormat(ctx)\n if (formatResult) return formatResult\n }\n\n // OAS 3.1: `contentMediaType: 'application/octet-stream'` on a string schema signals binary data.\n if (schema.type === 'string' && schema.contentMediaType === 'application/octet-stream') {\n return createSchema({ type: 'blob', primitive: 'string', ...renderSchemaBase(schema, name, nullable, defaultValue) })\n }\n\n // OAS 3.1: `type` may be an array — e.g. `[\"string\", \"integer\", \"null\"]`.\n // `null` in the array is the 3.1 equivalent of `nullable: true`; strip it and set the flag.\n // When 2+ non-null types remain, produce a union; when exactly 1 non-null type remains, fall through.\n if (Array.isArray(schema.type) && schema.type.length > 1) {\n const nonNullTypes = schema.type.filter((t) => t !== 'null') as string[]\n const arrayNullable = schema.type.includes('null') || nullable || undefined\n\n if (nonNullTypes.length > 1) {\n return createSchema({\n type: 'union',\n members: nonNullTypes.map((t) => convertSchema({ schema: { ...schema, type: t } as SchemaObject, name }, options)),\n ...renderSchemaBase(schema, name, arrayNullable, defaultValue),\n })\n }\n }\n\n // Infer type from constraints when no explicit type is provided.\n // minLength / maxLength / pattern → string; minimum / maximum → number.\n // Note: minItems/maxItems do NOT infer array — arrays require an `items` key.\n if (!type) {\n if (schema.minLength !== undefined || schema.maxLength !== undefined || schema.pattern !== undefined) {\n return convertString(ctx)\n }\n if (schema.minimum !== undefined || schema.maximum !== undefined) {\n return convertNumeric(ctx, 'number')\n }\n }\n\n if (schema.enum?.length) return convertEnum(ctx)\n if (type === 'object' || schema.properties || schema.additionalProperties || 'patternProperties' in schema) return convertObject(ctx)\n if ('prefixItems' in schema) return convertTuple(ctx)\n if (type === 'array' || 'items' in schema) return convertArray(ctx)\n if (type === 'string') return convertString(ctx)\n if (type === 'number') return convertNumeric(ctx, 'number')\n if (type === 'integer') return convertNumeric(ctx, 'integer')\n if (type === 'boolean') return convertBoolean(ctx)\n if (type === 'null') return convertNull(ctx)\n\n const emptyType = resolveTypeOption(mergedOptions.emptySchemaType)\n return createSchema({ type: emptyType as ScalarSchemaType, name, title: schema.title, description: schema.description })\n }\n\n /**\n * Converts a single dereferenced OAS parameter object into a `ParameterNode`.\n * When the parameter has no `schema`, falls back to `unknownType`; `$ref` schemas are resolved through `convertSchema` to produce a proper named type reference.\n */\n function parseParameter(options: ParserOptions, param: Record<string, unknown>): ParameterNode {\n const required = (param['required'] as boolean | undefined) ?? false\n\n const schema: SchemaNode = param['schema']\n ? convertSchema({ schema: param['schema'] as SchemaObject }, options)\n : createSchema({ type: resolveTypeOption(options.unknownType) })\n\n return createParameter({\n name: param['name'] as string,\n in: param['in'] as ParameterLocation,\n schema: {\n ...schema,\n description: (param['description'] as string | undefined) ?? schema.description,\n optional: !required || !!schema.optional ? true : undefined,\n },\n required,\n })\n }\n\n /**\n * Converts an OAS `Operation` into an `OperationNode`, resolving parameters,\n * request body, and all response codes into their AST node equivalents.\n */\n function parseOperation(options: ParserOptions, oas: Oas, operation: Operation): OperationNode {\n const parameters: Array<ParameterNode> = oas.getParameters(operation).map((param) => parseParameter(options, param as unknown as Record<string, unknown>))\n\n const requestBodySchema = oas.getRequestSchema(operation)\n const requestBodySchemaNode = requestBodySchema ? convertSchema({ schema: requestBodySchema }, options) : undefined\n\n const requestBodyDescription =\n operation.schema.requestBody && !isReference(operation.schema.requestBody)\n ? (operation.schema.requestBody as { description?: string }).description\n : undefined\n\n const requestBodyKeysToOmit = requestBodySchema?.properties\n ? Object.entries(requestBodySchema.properties)\n .filter(([, prop]) => !isReference(prop) && (prop as { readOnly?: boolean }).readOnly)\n .map(([key]) => key)\n : undefined\n\n const requestBody = requestBodySchemaNode\n ? {\n description: requestBodyDescription,\n schema: requestBodySchemaNode,\n keysToOmit: requestBodyKeysToOmit?.length ? requestBodyKeysToOmit : undefined,\n }\n : undefined\n\n const responses: Array<ResponseNode> = operation.getResponseStatusCodes().map((statusCode) => {\n const responseObj = operation.getResponseByStatusCode(statusCode)\n const responseSchema = oas.getResponseSchema(operation, statusCode)\n\n const schema =\n responseSchema && Object.keys(responseSchema).length > 0\n ? convertSchema({ schema: responseSchema }, options)\n : createSchema({ type: resolveTypeOption(options.emptySchemaType) })\n\n const description = typeof responseObj === 'object' && responseObj !== null && !Array.isArray(responseObj) ? responseObj.description : undefined\n\n const rawContent =\n typeof responseObj === 'object' && responseObj !== null && !Array.isArray(responseObj)\n ? (responseObj as { content?: Record<string, unknown> }).content\n : undefined\n\n const mediaType = rawContent ? toMediaType(Object.keys(rawContent)[0] ?? '') : toMediaType(operation.contentType ?? '')\n\n const keysToOmit = responseSchema?.properties\n ? Object.entries(responseSchema.properties)\n .filter(([, prop]) => !isReference(prop) && (prop as { writeOnly?: boolean }).writeOnly)\n .map(([key]) => key)\n : undefined\n\n return createResponse({\n statusCode: statusCode as StatusCode,\n description,\n schema,\n mediaType,\n keysToOmit: keysToOmit?.length ? keysToOmit : undefined,\n })\n })\n\n return createOperation({\n operationId: operation.getOperationId(),\n method: operation.method.toUpperCase() as HttpMethod,\n path: new URLPath(operation.path).URL,\n tags: operation.getTags().map((tag) => tag.name),\n summary: operation.getSummary() || undefined,\n description: operation.getDescription() || undefined,\n deprecated: operation.isDeprecated() || undefined,\n parameters,\n requestBody,\n responses,\n })\n }\n\n /**\n * Converts an OpenAPI/Swagger spec (wrapped in a Kubb `Oas` instance) into\n * a `RootNode` — the top-level node of the `@kubb/ast` tree.\n */\n function parse<TOptions extends Partial<ParserOptions> = object>(options?: TOptions): RootNode {\n const mergedOptions: ParserOptions = { ...DEFAULT_PARSER_OPTIONS, ...options }\n\n const schemas: Array<SchemaNode> = Object.entries(schemaObjects).map(([name, schemaObject]) =>\n convertSchema({ schema: schemaObject as SchemaObject, name }, mergedOptions),\n )\n\n const paths = oas.getPaths()\n\n const operations: Array<OperationNode> = Object.entries(paths).flatMap(([_path, methods]) =>\n Object.entries(methods)\n .map(([, operation]) => (operation ? parseOperation(mergedOptions, oas, operation) : null))\n .filter((op): op is OperationNode => op !== null),\n )\n\n return createRoot({ schemas, operations })\n }\n\n /**\n * Walks a `SchemaNode` tree and resolves all `ref` node names through the provided callbacks.\n *\n * `resolveName` handles all schema types; `resolveEnumName` (when provided) takes precedence\n * for `enum` nodes, enabling a separate naming strategy for enums (e.g. different suffix).\n *\n * Collision-resolved names (from `nameMapping`) are applied before user-supplied resolvers.\n */\n function resolveRefs(node: SchemaNode, resolveName: (ref: string) => string | undefined, resolveEnumName?: (name: string) => string | undefined): SchemaNode {\n return transform(node, {\n schema(schemaNode) {\n const schemaRef = narrowSchema(schemaNode, schemaTypes.ref)\n\n if (schemaRef && (schemaRef.ref || schemaRef.name)) {\n const rawRef = schemaRef.ref ?? schemaRef.name!\n const resolved = resolveName(nameMapping.get(rawRef) ?? rawRef)\n if (resolved) {\n return { ...schemaNode, name: resolved }\n }\n }\n\n if (schemaNode.type === 'enum' && schemaNode.name) {\n const resolved = (resolveEnumName ?? resolveName)(schemaNode.name)\n if (resolved) {\n return { ...schemaNode, name: resolved }\n }\n }\n },\n }) as SchemaNode\n }\n\n return {\n parse,\n convertSchema,\n resolveRefs,\n nameMapping,\n } as OasParser\n}\n","import path from 'node:path'\nimport { createRoot } from '@kubb/ast'\nimport type { AdapterSource } from '@kubb/core'\nimport { createAdapter } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { resolveServerUrl } from './oas/resolveServerUrl.ts'\nimport { parseFromConfig } from './oas/utils.ts'\nimport { createOasParser } from './parser.ts'\nimport type { OasAdapter } from './types.ts'\nimport { getImports } from './utils.ts'\n\nexport const adapterOasName = 'oas' satisfies OasAdapter['name']\n\n/**\n * Creates an OpenAPI / Swagger adapter for Kubb.\n *\n * This is the default adapter — you can omit it from your config when using\n * an OpenAPI spec, but supplying it explicitly lets you pass options.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n *\n * export default defineConfig({\n * adapter: adapterOas({ validate: true, dateType: 'date' }),\n * input: { path: './openapi.yaml' },\n * plugins: [pluginTs(), pluginZod()],\n * })\n * ```\n */\nexport const adapterOas = createAdapter<OasAdapter>((options) => {\n const {\n validate = true,\n oasClass,\n contentType,\n serverIndex,\n serverVariables,\n discriminator = 'strict',\n collisionDetection = 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 // Mutable Map shared between `options` and each `parse()` call.\n // Populated (and replaced) on every parse so consumers always see the latest state.\n const nameMapping = new Map<string, string>()\n\n return {\n name: adapterOasName,\n options: {\n validate,\n oasClass,\n contentType,\n serverIndex,\n serverVariables,\n discriminator,\n collisionDetection,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n nameMapping,\n },\n getImports(node, resolve) {\n return getImports({ node, nameMapping, resolve })\n },\n async parse(source) {\n const fakeConfig = sourceToFakeConfig(source)\n const oas = await parseFromConfig(fakeConfig, oasClass)\n\n oas.setOptions({ contentType, discriminator, collisionDetection })\n\n if (validate) {\n try {\n await oas.validate()\n } catch (_err) {\n // Validation failures are non-fatal — mirror plugin-oas behavior\n }\n }\n\n const server = serverIndex !== undefined ? oas.api.servers?.at(serverIndex) : undefined\n const baseURL = server?.url ? resolveServerUrl(server, serverVariables) : undefined\n\n const parser = createOasParser(oas, { contentType, collisionDetection })\n const root = parser.parse({ dateType, integerType, unknownType, emptySchemaType, enumSuffix })\n\n // This must happen after parse() because legacy enum remapping is finalized there.\n nameMapping.clear()\n for (const [key, value] of parser.nameMapping) {\n nameMapping.set(key, value)\n }\n\n return createRoot({\n ...root,\n meta: {\n title: oas.api.info?.title,\n description: oas.api.info?.description,\n version: oas.api.info?.version,\n baseURL,\n },\n })\n },\n }\n})\n\n// TODO: remove once parseFromConfig accepts AdapterSource directly\nfunction sourceToFakeConfig(source: AdapterSource): Parameters<typeof parseFromConfig>[0] {\n switch (source.type) {\n case 'path':\n return { root: path.dirname(source.path), input: { path: source.path } } as Parameters<typeof parseFromConfig>[0]\n case 'data':\n return { root: process.cwd(), input: { data: source.data } } as Parameters<typeof parseFromConfig>[0]\n case 'paths':\n return {\n root: source.paths[0] ? path.dirname(source.paths[0]) : process.cwd(),\n input: source.paths.map((p) => ({ path: p })),\n } as Parameters<typeof parseFromConfig>[0]\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;CACb,aAAa;CACb,iBAAiB;CACjB,YAAY;CACb;;;;AAK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,MAAM;KAC3B,SAAS,IAAI,IAAI,MAAM;KACvB;KACD;IACF,CAAC;;EAEL;EACD;AAGF,SAAS,mBAAmB,QAA8D;AACxF,SAAQ,OAAO,MAAf;EACE,KAAK,OACH,QAAO;GAAE,MAAM,KAAK,QAAQ,OAAO,KAAK;GAAE,OAAO,EAAE,MAAM,OAAO,MAAM;GAAE;EAC1E,KAAK,OACH,QAAO;GAAE,MAAM,QAAQ,KAAK;GAAE,OAAO,EAAE,MAAM,OAAO,MAAM;GAAE;EAC9D,KAAK,QACH,QAAO;GACL,MAAM,OAAO,MAAM,KAAK,KAAK,QAAQ,OAAO,MAAM,GAAG,GAAG,QAAQ,KAAK;GACrE,OAAO,OAAO,MAAM,KAAK,OAAO,EAAE,MAAM,GAAG,EAAE;GAC9C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#options","#transformParam","#eachParam","#options","#applyDiscriminatorInheritance","#setDiscriminator","#getResponseBodyFactory"],"sources":["../src/constants.ts","../src/oas/resolveServerUrl.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/oas/Oas.ts","../src/oas/utils.ts","../src/utils.ts","../src/parser.ts","../src/adapter.ts"],"sourcesContent":["import type { SchemaType } from '@kubb/ast/types'\nimport type { HttpMethods as OASHttpMethods } from 'oas/types'\nimport type { ParserOptions } from './types.ts'\n\n/**\n * Default values for all `Options` fields.\n */\nexport const DEFAULT_PARSER_OPTIONS = {\n dateType: 'string',\n integerType: 'number',\n unknownType: 'any',\n emptySchemaType: 'any',\n enumSuffix: 'enum',\n} as const satisfies ParserOptions\n\n/**\n * OpenAPI version string written into merged document stubs.\n */\nexport const MERGE_OPENAPI_VERSION = '3.0.0' as const\n\n/**\n * Fallback `info.title` used when merging multiple API documents.\n */\nexport const MERGE_DEFAULT_TITLE = 'Merged API' as const\n\n/**\n * Fallback `info.version` used when merging multiple API documents.\n */\nexport const MERGE_DEFAULT_VERSION = '1.0.0' as const\n\n/**\n * JSON Schema keywords that indicate structural composition.\n * A schema fragment containing any of these keys must not be inlined into its\n * parent during `allOf` flattening — it carries semantic meaning of its own.\n */\nexport const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)\n\n/**\n * Maps OAS/JSON Schema `format` strings to their Kubb `SchemaType` equivalents.\n *\n * Only formats that need a type different from the raw OAS `type` are listed.\n * `int64`, `date-time`, `date`, and `time` are handled separately because their\n * mapping depends on runtime parser options.\n *\n * Note: `ipv4`, `ipv6`, and `hostname` map to `'url'` — the closest supported\n * scalar type in the Kubb AST, even though these are not strictly URLs.\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: 'url',\n ipv6: 'url',\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, SchemaType>\n\n/**\n * Exhaustive list of media types that Kubb recognizes.\n */\nexport const knownMediaTypes = new Set([\n 'application/json',\n 'application/xml',\n 'application/x-www-form-urlencoded',\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'application/graphql',\n 'multipart/form-data',\n 'text/plain',\n 'text/html',\n 'text/csv',\n 'text/xml',\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/svg+xml',\n 'audio/mpeg',\n 'video/mp4',\n] as const)\n\n/**\n * Vendor extension keys used to attach human-readable labels to enum values.\n * Checked in priority order: the first key found wins.\n */\nexport const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const\n\n/**\n * Scalar primitive schema types used for union member simplification.\n */\nexport const SCALAR_PRIMITIVE_TYPES = new Set(['string', 'number', 'integer', 'bigint', 'boolean'] as const)\n\n/**\n * Canonical HTTP method names for the Kubb OAS layer.\n * Keys are uppercase (used in generated code); values are the lowercase strings\n * that the `oas` library uses internally.\n *\n * TODO(v5): remove — use `httpMethods` from `@kubb/ast`\n */\nexport const httpMethods = {\n GET: 'get',\n POST: 'post',\n PUT: 'put',\n PATCH: 'patch',\n DELETE: 'delete',\n HEAD: 'head',\n OPTIONS: 'options',\n TRACE: 'trace',\n} as const satisfies Record<Uppercase<OASHttpMethods>, OASHttpMethods>\n","/**\n * Models one variable definition in an OpenAPI server object.\n */\ntype ServerVariable = {\n default?: string | number\n enum?: (string | number)[]\n}\n\n/**\n * Minimal shape of an OpenAPI server object.\n */\ntype ServerObject = {\n url: string\n variables?: Record<string, ServerVariable>\n}\n\n/**\n * Resolves an OpenAPI server URL by substituting `{variable}` placeholders.\n *\n * Resolution priority per variable:\n * 1. `overrides[key]` — caller-supplied value.\n * 2. `variable.default` — spec-defined default, coerced to `string`.\n * 3. Variable is left unreplaced when neither is available.\n *\n * Throws when an `overrides` value is not present in the variable's `enum` list.\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 Error(`Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`)\n }\n\n url = url.replaceAll(`{${key}}`, value)\n }\n\n return url\n}\n","type Options = {\n /** When `true`, dot-separated segments are split on `.` and joined with `/` after casing. */\n isFile?: boolean\n /** Text prepended before casing is applied. */\n prefix?: string\n /** Text appended before casing is applied. */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Splits `text` on `.` and applies `transformPart` to each segment.\n * The last segment receives `isLast = true`, all earlier segments receive `false`.\n * Segments are joined with `/` to form a file path.\n *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\n\n/**\n * Converts `text` to camelCase.\n * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n *\n * @example\n * camelCase('hello-world') // 'helloWorld'\n * camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n *\n * @example\n * pascalCase('hello-world') // 'HelloWorld'\n * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","/**\n * 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 a word with `_` when it is a reserved JavaScript/Java identifier\n * or starts with a digit.\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 */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /** The resolved URL string (Express-style or template literal, depending on context). */\n url: string\n /** Extracted path parameters as a key-value map, or `undefined` when the path has none. */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /** Controls whether the `url` is rendered as an Express path or a template literal. Defaults to `'path'`. */\n type?: 'path' | 'template'\n /** Optional transform applied to each extracted parameter name. */\n replacer?: (pathParam: string) => string\n /** When `true`, the result is serialized to a string expression instead of a plain object. */\n stringify?: boolean\n}\n\n/** Supported identifier casing strategies for path parameters. */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /** Casing strategy applied to path parameter names. Defaults to the original identifier. */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /** The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`. */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`). */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set. */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters. */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /** Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name. */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import jsonpointer from 'jsonpointer'\nimport BaseOas from 'oas'\nimport type { ParameterObject } from 'oas/types'\nimport { matchesMimeType } from 'oas/utils'\nimport type { contentType, DiscriminatorObject, Document, MediaTypeObject, Operation, ReferenceObject, ResponseObject, SchemaObject } from './types.ts'\nimport {\n extractSchemaFromContent,\n flattenSchema,\n isDiscriminator,\n isReference,\n resolveCollisions,\n type SchemaWithMetadata,\n sortSchemas,\n validate,\n} from './utils.ts'\n\n/**\n * Prefix used to create synthetic `$ref` values for anonymous (inline) discriminator schemas.\n * The suffix is the schema index within the discriminator's `oneOf`/`anyOf` array.\n * @example `#kubb-inline-0`\n */\nconst KUBB_INLINE_REF_PREFIX = '#kubb-inline-'\n\ntype OasOptions = {\n contentType?: contentType\n discriminator?: 'strict' | 'inherit'\n}\n\nexport class Oas extends BaseOas {\n #options: OasOptions = {\n discriminator: 'strict',\n }\n document: Document\n\n constructor(document: Document) {\n super(document, undefined)\n\n this.document = document\n }\n\n setOptions(options: OasOptions) {\n this.#options = {\n ...this.#options,\n ...options,\n }\n\n if (this.#options.discriminator === 'inherit') {\n this.#applyDiscriminatorInheritance()\n }\n }\n\n get options(): OasOptions {\n return this.#options\n }\n\n get<T = unknown>($ref: string): T | null {\n const origRef = $ref\n $ref = $ref.trim()\n if ($ref === '') {\n return null\n }\n if ($ref.startsWith('#')) {\n $ref = globalThis.decodeURIComponent($ref.substring(1))\n } else {\n return null\n }\n const current = jsonpointer.get(this.api, $ref)\n\n if (!current) {\n throw new Error(`Could not find a definition for ${origRef}.`)\n }\n return current as T\n }\n\n getKey($ref: string) {\n const key = $ref.split('/').pop()\n return key === '' ? undefined : key\n }\n set($ref: string, value: unknown) {\n $ref = $ref.trim()\n if ($ref === '') {\n return false\n }\n if ($ref.startsWith('#')) {\n $ref = globalThis.decodeURIComponent($ref.substring(1))\n\n jsonpointer.set(this.api, $ref, value)\n }\n }\n\n #setDiscriminator(schema: SchemaObject & { discriminator: DiscriminatorObject }): void {\n const { mapping = {}, propertyName } = schema.discriminator\n\n if (this.#options.discriminator === 'inherit') {\n Object.entries(mapping).forEach(([mappingKey, mappingValue]) => {\n if (mappingValue) {\n const childSchema = this.get<any>(mappingValue)\n if (!childSchema) {\n return\n }\n\n if (!childSchema.properties) {\n childSchema.properties = {}\n }\n\n const property = childSchema.properties[propertyName] as SchemaObject\n\n if (childSchema.properties) {\n childSchema.properties[propertyName] = {\n ...((childSchema.properties ? childSchema.properties[propertyName] : {}) as SchemaObject),\n enum: [...(property?.enum?.filter((value) => value !== mappingKey) ?? []), mappingKey],\n }\n\n childSchema.required =\n typeof childSchema.required === 'boolean' ? childSchema.required : [...new Set([...(childSchema.required ?? []), propertyName])]\n\n this.set(mappingValue, childSchema)\n }\n }\n })\n }\n }\n\n getDiscriminator(schema: SchemaObject | null): DiscriminatorObject | null {\n if (!isDiscriminator(schema) || !schema) {\n return null\n }\n\n const { mapping = {}, propertyName } = schema.discriminator\n\n /**\n * Helper to extract discriminator value from a schema.\n * Checks in order:\n * 1. Extension property matching propertyName (e.g., x-linode-ref-name)\n * 2. Property with const value\n * 3. Property with single enum value\n * 4. Title as fallback\n */\n const getDiscriminatorValue = (schema: SchemaObject | null): string | null => {\n if (!schema) {\n return null\n }\n\n // Check extension properties first (e.g., x-linode-ref-name)\n // Only check if propertyName starts with 'x-' to avoid conflicts with standard properties\n if (propertyName.startsWith('x-')) {\n const extensionValue = (schema as Record<string, unknown>)[propertyName]\n if (extensionValue && typeof extensionValue === 'string') {\n return extensionValue\n }\n }\n\n // Check if property has const value\n const propertySchema = schema.properties?.[propertyName] as SchemaObject\n if (propertySchema && 'const' in propertySchema && propertySchema.const !== undefined) {\n return String(propertySchema.const)\n }\n\n // Check if property has single enum value\n if (propertySchema && propertySchema.enum?.length === 1) {\n return String(propertySchema.enum[0])\n }\n\n // Fallback to title if available\n return schema.title || null\n }\n\n /**\n * Process oneOf/anyOf items to build mapping.\n * Handles both $ref and inline schemas.\n */\n const processSchemas = (schemas: Array<SchemaObject>, existingMapping: Record<string, string>) => {\n schemas.forEach((schemaItem, index) => {\n if (isReference(schemaItem)) {\n // Handle $ref case\n const key = this.getKey(schemaItem.$ref)\n\n try {\n const refSchema = this.get<SchemaObject>(schemaItem.$ref)\n const discriminatorValue = getDiscriminatorValue(refSchema)\n const canAdd = key && !Object.values(existingMapping).includes(schemaItem.$ref)\n\n if (canAdd && discriminatorValue) {\n existingMapping[discriminatorValue] = schemaItem.$ref\n } else if (canAdd) {\n existingMapping[key] = schemaItem.$ref\n }\n } catch (_error) {\n // If we can't resolve the reference, skip it and use the key as fallback\n if (key && !Object.values(existingMapping).includes(schemaItem.$ref)) {\n existingMapping[key] = schemaItem.$ref\n }\n }\n } else {\n // Handle inline schema case\n const inlineSchema = schemaItem as SchemaObject\n const discriminatorValue = getDiscriminatorValue(inlineSchema)\n\n if (discriminatorValue) {\n // Create a synthetic ref for inline schemas using index\n // The value points to the inline schema itself via a special marker\n existingMapping[discriminatorValue] = `${KUBB_INLINE_REF_PREFIX}${index}`\n }\n }\n })\n }\n\n // Process oneOf schemas\n if (schema.oneOf) {\n processSchemas(schema.oneOf as Array<SchemaObject>, mapping)\n }\n\n // Process anyOf schemas\n if (schema.anyOf) {\n processSchemas(schema.anyOf as Array<SchemaObject>, mapping)\n }\n\n return {\n ...schema.discriminator,\n mapping,\n }\n }\n\n // TODO add better typing\n dereferenceWithRef<T = unknown>(schema?: T): T {\n if (isReference(schema)) {\n return {\n ...schema,\n ...this.get(schema.$ref),\n $ref: schema.$ref,\n }\n }\n\n return schema as T\n }\n\n #applyDiscriminatorInheritance() {\n const components = this.api.components\n if (!components?.schemas) {\n return\n }\n\n const visited = new WeakSet<object>()\n const enqueue = (value: unknown) => {\n if (!value) {\n return\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n enqueue(item)\n }\n return\n }\n\n if (typeof value === 'object') {\n visit(value as SchemaObject)\n }\n }\n\n const visit = (schema?: SchemaObject | ReferenceObject | null) => {\n if (!schema || typeof schema !== 'object') {\n return\n }\n\n if (isReference(schema)) {\n visit(this.get(schema.$ref) as SchemaObject)\n return\n }\n\n const schemaObject = schema as SchemaObject\n\n if (visited.has(schemaObject as object)) {\n return\n }\n\n visited.add(schemaObject as object)\n\n if (isDiscriminator(schemaObject)) {\n this.#setDiscriminator(schemaObject)\n }\n\n if ('allOf' in schemaObject) {\n enqueue(schemaObject.allOf)\n }\n if ('oneOf' in schemaObject) {\n enqueue(schemaObject.oneOf)\n }\n if ('anyOf' in schemaObject) {\n enqueue(schemaObject.anyOf)\n }\n if ('not' in schemaObject) {\n enqueue(schemaObject.not)\n }\n if ('items' in schemaObject) {\n enqueue(schemaObject.items)\n }\n if ('prefixItems' in schemaObject) {\n enqueue(schemaObject.prefixItems)\n }\n\n if (schemaObject.properties) {\n enqueue(Object.values(schemaObject.properties))\n }\n\n if (schemaObject.additionalProperties && typeof schemaObject.additionalProperties === 'object') {\n enqueue(schemaObject.additionalProperties)\n }\n }\n\n for (const schema of Object.values(components.schemas)) {\n visit(schema as SchemaObject)\n }\n }\n\n /**\n * Oas does not have a getResponseBody(contentType)\n */\n #getResponseBodyFactory(responseBody: boolean | ResponseObject): (contentType?: string) => MediaTypeObject | false | [string, MediaTypeObject, ...string[]] {\n function hasResponseBody(res = responseBody): res is ResponseObject {\n return !!res\n }\n\n return (contentType) => {\n if (!hasResponseBody(responseBody)) {\n return false\n }\n\n if (isReference(responseBody)) {\n // If the request body is still a `$ref` pointer we should return false because this library\n // assumes that you've run dereferencing beforehand.\n return false\n }\n\n if (!responseBody.content) {\n return false\n }\n\n if (contentType) {\n if (!(contentType in responseBody.content)) {\n return false\n }\n\n return responseBody.content[contentType]!\n }\n\n // Since no media type was supplied we need to find either the first JSON-like media type that\n // we've got, or the first available of anything else if no JSON-like media types are present.\n let availableContentType: string | undefined\n const contentTypes = Object.keys(responseBody.content)\n contentTypes.forEach((mt: string) => {\n if (!availableContentType && matchesMimeType.json(mt)) {\n availableContentType = mt\n }\n })\n\n if (!availableContentType) {\n contentTypes.forEach((mt: string) => {\n if (!availableContentType) {\n availableContentType = mt\n }\n })\n }\n\n if (availableContentType) {\n return [availableContentType, responseBody.content[availableContentType]!, ...(responseBody.description ? [responseBody.description] : [])]\n }\n\n return false\n }\n }\n\n getResponseSchema(operation: Operation, statusCode: string | number): SchemaObject {\n if (operation.schema.responses) {\n Object.keys(operation.schema.responses).forEach((key) => {\n const schema = operation.schema.responses![key]\n const $ref = isReference(schema) ? schema.$ref : undefined\n\n if (schema && $ref) {\n operation.schema.responses![key] = this.get<any>($ref)\n }\n })\n }\n\n const getResponseBody = this.#getResponseBodyFactory(operation.getResponseByStatusCode(statusCode))\n\n const { contentType } = this.#options\n const responseBody = getResponseBody(contentType)\n\n if (responseBody === false) {\n // return empty object because response will always be defined(request does not need a body)\n return {}\n }\n\n const schema = Array.isArray(responseBody) ? responseBody[1].schema : responseBody.schema\n\n if (!schema) {\n // return empty object because response will always be defined(request does not need a body)\n\n return {}\n }\n\n return this.dereferenceWithRef(schema)\n }\n\n getRequestSchema(operation: Operation): SchemaObject | undefined {\n const { contentType } = this.#options\n\n if (operation.schema.requestBody) {\n operation.schema.requestBody = this.dereferenceWithRef(operation.schema.requestBody)\n }\n\n const requestBody = operation.getRequestBody(contentType)\n\n if (requestBody === false) {\n return undefined\n }\n\n const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema\n\n if (!schema) {\n return undefined\n }\n\n return this.dereferenceWithRef(schema)\n }\n\n /**\n * Returns all resolved parameters for an operation, merging path-level and operation-level\n * parameters and deduplicating by `in:name` (operation-level takes precedence).\n *\n * oas v31+ filters out `$ref` parameters in `getParameters()`, so this method accesses the\n * raw `operation.schema.parameters` and path-item parameters directly and resolves `$ref`\n * pointers via `dereferenceWithRef` to preserve backward compatibility.\n */\n getParameters(operation: Operation): Array<ParameterObject> {\n const resolveParams = (params: unknown[]): Array<ParameterObject> =>\n params.map((p) => this.dereferenceWithRef(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 = this.api?.paths?.[operation.path]\n const pathLevelParams = resolveParams(pathItem && !isReference(pathItem) && pathItem.parameters ? pathItem.parameters : [])\n\n // Deduplicate: operation-level parameters override path-level ones with the same name+in\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\n getParametersSchema(operation: Operation, inKey: 'path' | 'query' | 'header'): SchemaObject | null {\n const { contentType = operation.getContentType() } = this.#options\n\n const params = this.getParameters(operation).filter((v) => v.in === inKey)\n\n if (!params.length) {\n return null\n }\n\n return params.reduce(\n (schema, pathParameters) => {\n const property = (pathParameters.content?.[contentType]?.schema ?? (pathParameters.schema as SchemaObject)) as SchemaObject | null\n const required =\n typeof schema.required === 'boolean'\n ? schema.required\n : [...(schema.required || []), pathParameters.required ? pathParameters.name : undefined].filter(Boolean)\n\n // Handle explode=true with style=form for object with additionalProperties\n // According to OpenAPI spec, when explode is true, object properties are flattened\n const getDefaultStyle = (location: string): string => {\n if (location === 'query') return 'form'\n if (location === 'path') return 'simple'\n return 'simple'\n }\n const style = pathParameters.style || getDefaultStyle(inKey)\n const explode = pathParameters.explode !== undefined ? pathParameters.explode : style === 'form'\n\n if (\n inKey === 'query' &&\n style === 'form' &&\n explode === true &&\n property?.type === 'object' &&\n property?.additionalProperties &&\n !property?.properties\n ) {\n // When explode is true for an object with only additionalProperties,\n // flatten it to the root level by merging additionalProperties with existing schema.\n // This preserves other query parameters while allowing dynamic key-value pairs.\n return {\n ...schema,\n description: pathParameters.description || schema.description,\n deprecated: schema.deprecated,\n example: property.example || schema.example,\n additionalProperties: property.additionalProperties,\n } as SchemaObject\n }\n\n return {\n ...schema,\n description: schema.description,\n deprecated: schema.deprecated,\n example: schema.example,\n required,\n properties: {\n ...schema.properties,\n [pathParameters.name]: {\n description: pathParameters.description,\n ...property,\n },\n },\n } as SchemaObject\n },\n { type: 'object', required: [], properties: {} } as SchemaObject,\n )\n }\n\n async validate() {\n return validate(this.api)\n }\n\n flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n return flattenSchema(schema)\n }\n\n /**\n * Get schemas from OpenAPI components (schemas, responses, requestBodies).\n * Returns schemas in dependency order along with name mapping for collision resolution.\n */\n getSchemas(options: { contentType?: contentType; includes?: Array<'schemas' | 'responses' | 'requestBodies'> } = {}): {\n schemas: Record<string, SchemaObject>\n nameMapping: Map<string, string>\n } {\n const contentType = options.contentType ?? this.#options.contentType\n const includes = options.includes ?? ['schemas', 'requestBodies', 'responses']\n\n const components = this.getDefinition().components\n const schemasWithMeta: SchemaWithMetadata[] = []\n\n // Collect schemas from components\n if (includes.includes('schemas')) {\n const componentSchemas = (components?.schemas as Record<string, SchemaObject>) || {}\n for (const [name, schemaObject] of Object.entries(componentSchemas)) {\n // Resolve schema if it's a $ref (can happen when the bundler deduplicates schemas\n // referenced from multiple external files). Without this, a $ref schema would be\n // parsed as a reference to itself, generating `z.lazy(() => schemaName)`.\n let schema = schemaObject\n if (isReference(schemaObject)) {\n const resolved = this.get<SchemaObject>(schemaObject.$ref)\n if (resolved && !isReference(resolved)) {\n schema = resolved\n }\n }\n schemasWithMeta.push({ schema, source: 'schemas', originalName: name })\n }\n }\n\n if (includes.includes('responses')) {\n const responses = components?.responses || {}\n for (const [name, response] of Object.entries(responses)) {\n const responseObject = response as ResponseObject\n const schema = extractSchemaFromContent(responseObject.content, contentType)\n if (schema) {\n // Resolve schema if it's a $ref (can happen when the bundler deduplicates schemas\n // referenced from multiple external files). Without this, a $ref schema would be\n // parsed as a reference to itself, generating `z.lazy(() => schemaName)`.\n let resolvedSchema = schema\n if (isReference(schema)) {\n const resolved = this.get<SchemaObject>(schema.$ref)\n if (resolved && !isReference(resolved)) {\n resolvedSchema = resolved\n }\n }\n schemasWithMeta.push({ schema: resolvedSchema, source: 'responses', originalName: name })\n }\n }\n }\n\n if (includes.includes('requestBodies')) {\n const requestBodies = components?.requestBodies || {}\n for (const [name, request] of Object.entries(requestBodies)) {\n const requestObject = request as { content?: Record<string, unknown> }\n const schema = extractSchemaFromContent(requestObject.content, contentType)\n if (schema) {\n // Resolve schema if it's a $ref (can happen when the bundler deduplicates schemas\n // referenced from multiple external files). Without this, a $ref schema would be\n // parsed as a reference to itself, generating `z.lazy(() => schemaName)`.\n let resolvedSchema = schema\n if (isReference(schema)) {\n const resolved = this.get<SchemaObject>(schema.$ref)\n if (resolved && !isReference(resolved)) {\n resolvedSchema = resolved\n }\n }\n schemasWithMeta.push({ schema: resolvedSchema, source: 'requestBodies', originalName: name })\n }\n }\n }\n\n const { schemas, nameMapping } = resolveCollisions(schemasWithMeta)\n\n return {\n schemas: sortSchemas(schemas),\n nameMapping,\n }\n }\n}\n","import path from 'node:path'\nimport { pascalCase, URLPath } from '@internals/utils'\nimport type { Config } from '@kubb/core'\nimport { bundle, loadConfig } from '@redocly/openapi-core'\nimport yaml from '@stoplight/yaml'\nimport { isRef } from 'oas/types'\nimport OASNormalize from 'oas-normalize'\nimport type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\nimport { isPlainObject, mergeDeep } from 'remeda'\nimport swagger2openapi from 'swagger2openapi'\nimport { MERGE_DEFAULT_TITLE, MERGE_DEFAULT_VERSION, MERGE_OPENAPI_VERSION, structuralKeys } from '../constants.ts'\nimport { Oas } from './Oas.ts'\nimport type { contentType, Document, SchemaObject } from './types.ts'\n\n/**\n * Narrows `doc` to a Swagger 2.0 document.\n * Swagger 2.0 documents do not have an `openapi` version key.\n */\nexport function isOpenApiV2Document(doc: unknown): doc is OpenAPIV2.Document {\n return !!doc && isPlainObject(doc) && !('openapi' in doc)\n}\n\n/**\n * Narrows `doc` to an OpenAPI 3.x document.\n * Any document that has an `openapi` key is considered 3.x (including 3.1).\n */\nexport function isOpenApiV3Document(doc: unknown): doc is OpenAPIV3.Document {\n return !!doc && isPlainObject(doc) && 'openapi' in doc\n}\n\n/**\n * Narrows `doc` to an OpenAPI 3.1 document by checking the version prefix.\n */\nexport function isOpenApiV3_1Document(doc: unknown): doc is OpenAPIV3_1.Document {\n return !!doc && isPlainObject(doc) && 'openapi' in (doc as object) && (doc as { openapi: string }).openapi.startsWith('3.1')\n}\n\n/**\n * Returns `true` when a schema should be treated as nullable.\n *\n * Covers three nullable signals across OAS versions:\n * - OAS 3.0: `nullable: true` or the vendor extension `x-nullable: true`.\n * - OAS 3.1 / JSON Schema: `type: 'null'` or `type: ['null', ...]` (multi-type array).\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 * Narrows `obj` to an OpenAPI `$ref` pointer object.\n * Delegates to the `oas` package's own `isRef` helper.\n */\nexport function isReference(obj?: unknown): obj is OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject {\n return !!obj && isRef(obj as object)\n}\n\n/**\n * Returns `true` when `obj` is a schema that carries a structured OAS 3.x `discriminator`\n * object — as opposed to a plain-string discriminator found in some Swagger 2 specs.\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: OpenAPIV3.DiscriminatorObject } {\n const record = obj as Record<string, unknown>\n return !!obj && !!record['discriminator'] && typeof record['discriminator'] !== 'string'\n}\n\n/**\n * Loads, dereferences, and wraps a raw OpenAPI document into an `Oas` instance.\n *\n * When given a file path string with `canBundle: true` (the default), Redocly's\n * bundler resolves all external `$ref`s first. Swagger 2.0 documents are\n * automatically up-converted to OpenAPI 3.0 via `swagger2openapi`.\n */\nexport async function parse(\n pathOrApi: string | Document,\n { oasClass = Oas, canBundle = true, enablePaths = true }: { oasClass?: typeof Oas; canBundle?: boolean; enablePaths?: boolean } = {},\n): Promise<Oas> {\n if (typeof pathOrApi === 'string' && canBundle) {\n const config = await loadConfig()\n const bundleResults = await bundle({ ref: pathOrApi, config, base: pathOrApi })\n\n return parse(bundleResults.bundle.parsed as string, { oasClass, canBundle, enablePaths })\n }\n\n const oasNormalize = new OASNormalize(pathOrApi, {\n enablePaths,\n colorizeErrors: true,\n })\n const document = (await oasNormalize.load()) as Document\n\n if (isOpenApiV2Document(document)) {\n const { openapi } = await swagger2openapi.convertObj(document, {\n anchors: true,\n })\n\n return new oasClass(openapi as Document)\n }\n\n return new oasClass(document)\n}\n\n/**\n * Deep-merges multiple OpenAPI documents into a single `Oas` instance.\n *\n * Each document is parsed independently (without path dereferencing) and then\n * recursively merged using `remeda`'s `mergeDeep`. The result is re-parsed so\n * the returned `Oas` instance is fully initialized.\n *\n * Throws when the input array is empty — at least one document is required.\n */\nexport async function merge(pathOrApi: Array<string | Document>, { oasClass = Oas }: { oasClass?: typeof Oas } = {}): Promise<Oas> {\n const instances = await Promise.all(pathOrApi.map((p) => parse(p, { oasClass, enablePaths: false, canBundle: false })))\n\n if (instances.length === 0) {\n throw new Error('No OAS instances provided for merging.')\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 = instances.reduce((acc, current) => mergeDeep(acc, current.document as Document), seed)\n\n return parse(merged, { oasClass })\n}\n\n/**\n * Constructs an `Oas` instance from a Kubb `Config` object.\n *\n * Handles all three input forms supported by `Config`:\n * - `data` — an inline YAML string, JSON string, or pre-parsed object.\n * - Array — multiple file paths that are deep-merged via {@link merge}.\n * - `path` — a local file path or a remote URL.\n */\nexport function parseFromConfig(config: Config, oasClass: typeof Oas = Oas): Promise<Oas> {\n if ('data' in config.input) {\n if (typeof config.input.data === 'object') {\n return parse(structuredClone(config.input.data) as Document, { oasClass })\n }\n\n try {\n const api: string = yaml.parse(config.input.data as string)\n return parse(api, { oasClass })\n } catch {\n return parse(config.input.data as string, { oasClass })\n }\n }\n\n if (Array.isArray(config.input)) {\n return merge(\n config.input.map((input) => path.resolve(config.root, input.path)),\n { oasClass },\n )\n }\n\n if (new URLPath(config.input.path).isURL) {\n return parse(config.input.path, { oasClass })\n }\n\n return parse(path.resolve(config.root, config.input.path), { oasClass })\n}\n\n/**\n * Flattens a single-member or keyword-only `allOf` into its parent schema.\n *\n * Flattening is only performed when every `allOf` member is a \"plain fragment\" —\n * i.e. contains no structural composition keywords (see `structuralKeys`) and no\n * `$ref`. When any member carries structural meaning, the schema is returned unchanged.\n *\n * Keyword values from allOf members are merged into the parent on a first-write basis:\n * outer schema values always win over fragment values.\n */\nexport function flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null\n if (schema.allOf.some((item) => isRef(item))) return schema\n\n const isPlainFragment = (item: SchemaObject) => !Object.keys(item).some((key) => structuralKeys.has(key as 'properties'))\n if (!schema.allOf.every((item) => isPlainFragment(item as SchemaObject))) return schema\n\n const merged: SchemaObject = { ...schema }\n delete merged.allOf\n\n for (const fragment of schema.allOf as SchemaObject[]) {\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 * Validates an OpenAPI document using `oas-normalize`.\n * Enables path validation and colorized error output.\n */\nexport async function validate(document: Document) {\n const oasNormalize = new OASNormalize(document, {\n enablePaths: true,\n colorizeErrors: true,\n })\n\n return oasNormalize.validate({\n parser: {\n validate: {\n errors: { colorize: true },\n },\n },\n })\n}\n\n/**\n * Discriminates the three component sources Kubb reads schemas from.\n */\ntype SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'\n\nexport type SchemaWithMetadata = {\n schema: SchemaObject\n source: SchemaSourceMode\n originalName: string\n}\n\ntype GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n nameMapping: Map<string, string>\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` refs.\n * Used by `sortSchemas` to build the dependency graph.\n */\nfunction collectRefs(schema: unknown, refs = new Set<string>()): Set<string> {\n if (Array.isArray(schema)) {\n for (const item of schema) collectRefs(item, refs)\n return refs\n }\n\n if (schema && typeof schema === 'object') {\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$ref' && typeof value === 'string') {\n const match = value.match(/^#\\/components\\/schemas\\/(.+)$/)\n if (match) refs.add(match[1]!)\n } else {\n collectRefs(value, refs)\n }\n }\n }\n\n return refs\n}\n\n/**\n * Returns a copy of `schemas` topologically sorted by `$ref` dependency.\n *\n * Schemas with no references come first; schemas that are referenced by others\n * come before those that reference them. This ensures code generators emit\n * referenced types before the types that depend on them.\n *\n * Cycles are silently skipped via the `stack` guard inside `visit`.\n */\nexport function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {\n const deps = new Map<string, string[]>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n deps.set(name, Array.from(collectRefs(schema)))\n }\n\n const sorted: 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\n/**\n * Extracts the inline schema from a media-type `content` map.\n *\n * Prefers `preferredContentType` when provided; otherwise falls back to the\n * first key in the map. Returns `null` when:\n * - `content` is absent.\n * - The target content-type has no `schema` entry.\n * - The schema is a `$ref` (callers resolve refs separately).\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 * Returns the PascalCase suffix appended to a component name when resolving\n * cross-source name collisions (schemas vs. responses vs. requestBodies).\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\n/**\n * Builds `GetSchemasResult` without any collision detection.\n * Each schema is registered under its original component name and its full\n * `#/components/<source>/<name>` ref path.\n */\nexport function legacyResolve(schemasWithMeta: SchemaWithMetadata[]): GetSchemasResult {\n const schemas: Record<string, SchemaObject> = {}\n const nameMapping = new Map<string, string>()\n\n for (const item of schemasWithMeta) {\n schemas[item.originalName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, item.originalName)\n }\n\n return { schemas, nameMapping }\n}\n\n/**\n * Builds `GetSchemasResult` with automatic name-collision resolution.\n *\n * When two or more schemas normalize to the same PascalCase name:\n * - If they share the same source, a numeric suffix (`2`, `3`, …) is appended.\n * - If they come from different sources (schemas / responses / requestBodies),\n * a semantic suffix (`Schema`, `Response`, `Request`) is appended.\n *\n * Non-colliding schemas are left unchanged.\n */\nexport function resolveCollisions(schemasWithMeta: SchemaWithMetadata[]): GetSchemasResult {\n const schemas: Record<string, SchemaObject> = {}\n const nameMapping = new Map<string, string>()\n const normalizedNames = new Map<string, SchemaWithMetadata[]>()\n\n for (const item of schemasWithMeta) {\n const normalized = pascalCase(item.originalName)\n const bucket = normalizedNames.get(normalized) ?? []\n bucket.push(item)\n normalizedNames.set(normalized, bucket)\n }\n\n for (const [, items] of normalizedNames) {\n if (items.length === 1) {\n const item = items[0]!\n schemas[item.originalName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, item.originalName)\n continue\n }\n\n const sources = new Set(items.map((item) => item.source))\n\n if (sources.size === 1) {\n items.forEach((item, index) => {\n const uniqueName = item.originalName + (index === 0 ? '' : (index + 1).toString())\n schemas[uniqueName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n } else {\n items.forEach((item) => {\n const uniqueName = item.originalName + getSemanticSuffix(item.source)\n schemas[uniqueName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n }\n }\n\n return { schemas, nameMapping }\n}\n","import { collect, createProperty, createSchema, narrowSchema } from '@kubb/ast'\nimport type { SchemaNode } from '@kubb/ast/types'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport { SCALAR_PRIMITIVE_TYPES } from './constants.ts'\n\n/**\n * Extracts the schema name from a `$ref` string.\n * For `#/components/schemas/Order` this returns `'Order'`.\n * Falls back to the full ref string when no slash is present.\n */\nexport function extractRefName($ref: string): string {\n return $ref.split('/').at(-1) ?? $ref\n}\n\n/**\n * Replaces the discriminator property's schema inside an `ObjectSchemaNode`\n * with an enum of the given `values`.\n *\n * - When `enumName` is provided the enum is named, which lets printers emit a\n * standalone enum declaration + type reference (e.g. `PetTypeEnum`).\n * - When `enumName` is omitted the enum stays anonymous, so printers inline it\n * as a literal union (e.g. `'dog'`).\n *\n * Returns the node unchanged when it is not an object or lacks the target property.\n */\nexport function applyDiscriminatorEnum({\n node,\n propertyName,\n values,\n enumName,\n}: {\n node: SchemaNode\n propertyName: string\n values: Array<string>\n enumName?: string\n}): SchemaNode {\n if (node.type !== 'object' || !node.properties?.length) return node\n\n const hasProperty = node.properties.some((prop) => prop.name === propertyName)\n if (!hasProperty) return node\n\n return createSchema({\n ...node,\n properties: node.properties.map((prop) => {\n if (prop.name !== propertyName) return prop\n\n const enumSchema: SchemaNode = createSchema({\n type: 'enum' as const,\n primitive: 'string' as const,\n enumValues: values,\n name: enumName,\n readOnly: prop.schema.readOnly,\n writeOnly: prop.schema.writeOnly,\n })\n\n return createProperty({\n ...prop,\n schema: enumSchema,\n })\n }),\n })\n}\n\n/**\n * Merges consecutive anonymous (`name`-less) `ObjectSchemaNode`s in `members` into a\n * single object by combining their `properties` arrays.\n *\n * Only adjacent pairs are merged — non-object or named nodes act as boundaries.\n * This collapses patterns like `Address & { streetNumber } & { streetName }` into\n * `Address & { streetNumber; streetName }`.\n */\nexport function mergeAdjacentAnonymousObjects(members: Array<SchemaNode>): Array<SchemaNode> {\n return members.reduce<Array<SchemaNode>>((acc, member) => {\n const obj = narrowSchema(member, 'object')\n if (obj && !obj.name) {\n const prev = acc[acc.length - 1]\n const prevObj = prev ? narrowSchema(prev, 'object') : null\n if (prevObj && !prevObj.name) {\n acc[acc.length - 1] = createSchema({\n ...prevObj,\n properties: [...(prevObj.properties ?? []), ...(obj.properties ?? [])],\n }) as SchemaNode\n return acc\n }\n }\n acc.push(member)\n return acc\n }, [])\n}\n\n/**\n * Simplifies a union member list by removing `enum` nodes whose `primitive` type is\n * already represented by a broader scalar node in the same union.\n *\n * For example `['placed', 'approved'] | string` collapses to `string` because\n * `string` subsumes all string literals. `'' | string` similarly becomes `string`.\n *\n * Only scalar primitives (`string`, `number`, `integer`, `bigint`, `boolean`) are\n * considered — object, array, and ref members are left untouched.\n *\n * Const-derived enums (those without an `enumType`, produced from an OpenAPI `const`\n * keyword) are **never** removed — `'accepted' | string` must stay as-is because the\n * literal is intentional.\n */\nexport function simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {\n const scalarPrimitives = new Set(members.filter((m) => SCALAR_PRIMITIVE_TYPES.has(m.type as 'string')).map((m) => m.type as string))\n if (!scalarPrimitives.size) return members\n\n return members.filter((m) => {\n if (m.type !== 'enum') return true\n const prim = m.primitive\n // Keep the enum if its primitive isn't fully subsumed.\n if (!prim) return true\n // Const-derived enums have no `enumType`; keep them as intentional literals.\n if (!m.enumType) return true\n // `number` subsumes `integer` literals and vice-versa for our purposes.\n if (scalarPrimitives.has(prim)) return false\n if ((prim === 'integer' || prim === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false\n return true\n })\n}\n\n/**\n * `nameMapping`, and calls `resolve` to obtain the `{ name, path }` pair for\n * each import. When `oas` is supplied, only `$ref`s that are resolvable in the\n * spec are included; omit it to skip the existence check.\n *\n * This function is the pure, state-free alternative to `OasParser.getImports`.\n * Because it receives `nameMapping` explicitly it can be called without holding\n * a reference to the parser or the OAS instance.\n *\n * @example\n * ```ts\n * // Use adapter state directly — no parser reference needed\n * const imports = getImports({\n * node: schemaNode,\n * nameMapping: adapter.options.nameMapping,\n * resolve: (schemaName) => ({\n * name: schemaManager.getName(schemaName, { type: 'type' }),\n * path: schemaManager.getFile(schemaName).path,\n * }),\n * })\n * ```\n */\nexport function getImports({\n node,\n nameMapping,\n resolve,\n}: {\n node: SchemaNode\n nameMapping: Map<string, string>\n resolve: (schemaName: string) => { name: string; path: string } | undefined\n}): Array<KubbFile.Import> {\n return collect<KubbFile.Import>(node, {\n schema(schemaNode): KubbFile.Import | undefined {\n if (schemaNode.type !== 'ref' || !schemaNode.ref) return\n\n const rawName = extractRefName(schemaNode.ref)\n\n // Apply collision-resolved name if available.\n const schemaName = nameMapping.get(rawName) ?? rawName\n const result = resolve(schemaName)\n if (!result) return\n\n return { name: [result.name], path: result.path }\n },\n })\n}\n","import { pascalCase, URLPath } from '@internals/utils'\nimport { createOperation, createParameter, createProperty, createResponse, createRoot, createSchema, narrowSchema, schemaTypes, transform } from '@kubb/ast'\nimport type {\n ArraySchemaNode,\n DateSchemaNode,\n DatetimeSchemaNode,\n EnumSchemaNode,\n HttpMethod,\n IntersectionSchemaNode,\n MediaType,\n NumberSchemaNode,\n ObjectSchemaNode,\n OperationNode,\n ParameterLocation,\n ParameterNode,\n PrimitiveSchemaType,\n PropertyNode,\n RefSchemaNode,\n ResponseNode,\n RootNode,\n ScalarSchemaNode,\n ScalarSchemaType,\n SchemaNode,\n SchemaType,\n StatusCode,\n StringSchemaNode,\n TimeSchemaNode,\n UnionSchemaNode,\n} from '@kubb/ast/types'\nimport { DEFAULT_PARSER_OPTIONS, enumExtensionKeys, formatMap, knownMediaTypes } from './constants.ts'\nimport type { Oas } from './oas/Oas.ts'\nimport type { contentType, Operation, ReferenceObject, SchemaObject } from './oas/types.ts'\nimport { flattenSchema, isDiscriminator, isNullable, isReference } from './oas/utils.ts'\nimport type { ParserOptions } from './types.ts'\nimport { applyDiscriminatorEnum, extractRefName, mergeAdjacentAnonymousObjects, simplifyUnionMembers } from './utils.ts'\n\n/**\n * Distributive `Omit` — correctly distributes over union types so that\n * `Omit<A | B, 'kind'>` produces `Omit<A, 'kind'> | Omit<B, 'kind'>`\n * rather than `Omit<A | B, 'kind'>`.\n */\ntype DistributiveOmit<TValue, TKey extends PropertyKey> = TValue extends unknown ? Omit<TValue, TKey> : never\n\n/**\n * Maps each `dateType` option value to the AST node produced by `format: 'date-time'`.\n */\ntype DateTimeNodeByDateType = {\n date: DateSchemaNode\n string: DatetimeSchemaNode\n stringOffset: DatetimeSchemaNode\n stringLocal: DatetimeSchemaNode\n false: StringSchemaNode\n}\n\n/**\n * Resolves the AST node produced by `format: 'date-time'` based on the `dateType` option.\n */\ntype ResolveDateTimeNode<TDateType extends ParserOptions['dateType']> = DateTimeNodeByDateType[TDateType extends keyof DateTimeNodeByDateType\n ? TDateType\n : 'string']\n\n/**\n * Single source of truth: ordered list of `[shape, SchemaNode]` pairs.\n * `InferSchemaNode` walks this tuple in order and returns the node type of the first matching entry.\n * Parameterized over `TDateType` so `format: 'date-time'` resolves to the correct node based on the option.\n */\ntype SchemaNodeMap<TDateType extends ParserOptions['dateType'] = 'string'> = [\n [{ $ref: string }, RefSchemaNode],\n // allOf with sibling `properties` always produces an intersection (shared props are appended as a member).\n [{ allOf: ReadonlyArray<unknown>; properties: object }, IntersectionSchemaNode],\n // allOf with 2+ members always produces an intersection.\n [{ allOf: readonly [unknown, unknown, ...unknown[]] }, IntersectionSchemaNode],\n // Single-member allOf without sibling `properties` flattens to the member type.\n [{ allOf: ReadonlyArray<unknown> }, SchemaNode],\n [{ oneOf: ReadonlyArray<unknown> }, UnionSchemaNode],\n [{ anyOf: ReadonlyArray<unknown> }, UnionSchemaNode],\n [{ const: null }, ScalarSchemaNode],\n [{ const: string | number | boolean }, EnumSchemaNode],\n // OAS 3.1 multi-type array: `{ type: ['string', 'integer'] }` → union node.\n [{ type: ReadonlyArray<string> }, UnionSchemaNode],\n // `{ type: 'array', enum }` is normalized at runtime: enum moves into items → array node.\n [{ type: 'array'; enum: ReadonlyArray<unknown> }, ArraySchemaNode],\n [{ enum: ReadonlyArray<unknown> }, EnumSchemaNode],\n [{ type: 'object' }, ObjectSchemaNode],\n [{ additionalProperties: boolean | {} }, ObjectSchemaNode],\n [{ type: 'array' }, ArraySchemaNode],\n [{ items: object }, ArraySchemaNode],\n [{ prefixItems: ReadonlyArray<unknown> }, ArraySchemaNode],\n // Format entries with explicit type — placed before generic type entries so format wins.\n [{ type: string; format: 'date-time' }, ResolveDateTimeNode<TDateType>],\n [{ type: string; format: 'date' }, DateSchemaNode],\n [{ type: string; format: 'time' }, TimeSchemaNode],\n [{ format: 'date-time' }, ResolveDateTimeNode<TDateType>],\n [{ format: 'date' }, DateSchemaNode],\n [{ format: 'time' }, TimeSchemaNode],\n [{ type: 'string' }, StringSchemaNode],\n [{ type: 'number' }, NumberSchemaNode],\n [{ type: 'integer' }, NumberSchemaNode],\n [{ type: 'bigint' }, NumberSchemaNode],\n [{ type: string }, ScalarSchemaNode],\n // Inferred scalar types from constraints when no explicit type is present.\n [{ minLength: number }, StringSchemaNode],\n [{ maxLength: number }, StringSchemaNode],\n [{ pattern: string }, StringSchemaNode],\n [{ minimum: number }, NumberSchemaNode],\n [{ maximum: number }, NumberSchemaNode],\n]\n\nexport type InferSchemaNode<\n TSchema extends SchemaObject,\n TDateType extends ParserOptions['dateType'] = 'string',\n TEntries extends ReadonlyArray<[object, SchemaNode]> = SchemaNodeMap<TDateType>,\n> = TEntries extends [infer TEntry extends [object, SchemaNode], ...infer TRest extends ReadonlyArray<[object, SchemaNode]>]\n ? TSchema extends TEntry[0]\n ? TEntry[1]\n : InferSchemaNode<TSchema, TDateType, TRest>\n : SchemaNode\n\n/**\n * Construction-time options for `createOasParser`.\n */\nexport type OasParserOptions = {\n contentType?: contentType\n}\n\n/**\n * Looks up the Kubb `SchemaType` for a given OAS `format` string.\n * Returns `undefined` for formats not in `formatMap` (e.g. `int64`, `date-time`),\n * which are handled separately because their output depends on parser options.\n */\nfunction formatToSchemaType(format: string): SchemaType | undefined {\n return formatMap[format as keyof typeof formatMap]\n}\n\n/**\n * Maps an OAS primitive type string to its `PrimitiveSchemaType` equivalent.\n * Numeric types (`number`, `integer`, `bigint`) are returned unchanged;\n * `boolean` maps to `'boolean'`; everything else defaults to `'string'`.\n */\nfunction getPrimitiveType(type: string | undefined): PrimitiveSchemaType {\n if (type === 'number' || type === 'integer' || type === 'bigint') return type\n if (type === 'boolean') return 'boolean'\n return 'string'\n}\n\n/**\n * Narrows a raw content-type string to the `MediaType` union recognized by Kubb.\n * Returns `undefined` for content types not present in `KNOWN_MEDIA_TYPES`.\n */\nfunction toMediaType(contentType: string): MediaType | undefined {\n return knownMediaTypes.has(contentType as MediaType) ? (contentType as MediaType) : undefined\n}\n\n/**\n * Pre-computed per-schema context passed to every `convert*` branch handler.\n * Grouping these values avoids repeating the same derivations across all branches.\n */\ntype SchemaContext = {\n schema: SchemaObject\n name: string | 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 options: Partial<ParserOptions> | undefined\n mergedOptions: ParserOptions\n}\n\n/**\n * The public interface returned by `createOasParser`.\n */\nexport type OasParser = {\n /**\n * Converts an OpenAPI/Swagger spec (wrapped in a Kubb `Oas` instance) into\n * a `RootNode` — the top-level node of the `@kubb/ast` tree.\n */\n parse: <TOptions extends Partial<ParserOptions> = object>(options?: TOptions) => RootNode\n convertSchema: <TFormat extends string, TSchema extends SchemaObject & { format?: TFormat }, TOptions extends Partial<ParserOptions> = object>(\n params: { schema: TSchema; name?: string },\n options?: TOptions,\n ) => InferSchemaNode<TSchema, TOptions extends { dateType: ParserOptions['dateType'] } ? TOptions['dateType'] : 'string'>\n /**\n * Walks `node` and replaces each `ref` value with the name returned by\n * `resolveName`. The callback receives the full `$ref` path (e.g. `#/components/schemas/Order`)\n * when available, falling back to the short name. Pass a no-op (`(n) => n`) to skip resolution.\n *\n * The optional `resolveEnumName` callback is called for inline `enum` nodes and should return\n * the transformed name to use (e.g. with a plugin `transformers.name` applied).\n */\n resolveRefs: (node: SchemaNode, resolveName: (ref: string) => string | undefined, resolveEnumName?: (name: string) => string | undefined) => SchemaNode\n\n /**\n * Map from original `$ref` paths to their collision-resolved schema names.\n * e.g. `'#/components/schemas/Order'` → `'OrderSchema'`\n *\n * Pass this to the standalone `getImports()` to resolve imports without holding\n * a reference to the full parser or OAS instance.\n */\n nameMapping: Map<string, string>\n}\n\n/**\n * Creates an OAS parser that converts an OpenAPI/Swagger spec into\n * the `@kubb/ast` tree.\n *\n * Options are passed per-call to `parse` or `convertSchema` rather than\n * at construction time, keeping the factory lightweight.\n *\n * This is the **kubb-parser** stage of the compilation lifecycle:\n * OpenAPI / Swagger → Kubb AST\n *\n * No code is generated here; the resulting tree is spec-agnostic and can\n * be consumed by any downstream plugin (plugin-ts, plugin-zod, …).\n *\n * @example\n * ```ts\n * const parser = createOasParser(oas)\n * const root = parser.parse({ emptySchemaType: 'unknown' })\n * ```\n */\nexport function createOasParser(oas: Oas, { contentType }: OasParserOptions = {}): OasParser {\n // Map from original component paths to resolved schema names (after collision resolution)\n // e.g., { '#/components/schemas/Order': 'OrderSchema', '#/components/responses/Product': 'ProductResponse' }\n const { schemas: schemaObjects, nameMapping } = oas.getSchemas({ contentType })\n\n /**\n * Maps an `'any' | 'unknown' | 'void'` option string to the corresponding `SchemaType` constant.\n * Used for both `unknownType` (unannotated schemas) and `emptySchemaType` (empty `{}` schemas).\n */\n function resolveTypeOption(value: 'any' | 'unknown' | 'void'): ScalarSchemaType {\n if (value === 'any') return schemaTypes.any\n if (value === 'void') return schemaTypes.void\n return schemaTypes.unknown\n }\n\n /**\n * Resolves the AST type and datetime modifiers for a date/time format, honoring the `dateType` option.\n * Returns `undefined` when `dateType` is `false`, meaning the format should fall through to `string`.\n */\n function getDateType(\n options: ParserOptions,\n format: 'date-time' | 'date' | 'time',\n ): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | undefined {\n if (!options.dateType) {\n return undefined\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 { type: 'date', representation: options.dateType === 'date' ? 'date' : 'string' }\n }\n\n // time\n return { type: 'time', representation: options.dateType === 'date' ? 'date' : 'string' }\n }\n\n /**\n * Shared metadata fields included in every `createSchema` call.\n * Centralizes the common properties so sub-handlers don't repeat them.\n */\n function renderSchemaBase(schema: SchemaObject, name: string | 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 } as const\n }\n\n // Branch handlers — each converts one OAS schema pattern to a SchemaNode.\n // They are defined as function declarations so they can reference each other\n // and `convertSchema` freely (JS hoisting).\n\n /**\n * Converts a `$ref` schema pointer into a `RefSchemaNode`.\n *\n * In OAS 3.0 siblings of `$ref` are technically ignored by the spec, but Kubb intentionally\n * preserves them so that annotations like `pattern`, `description`, and `nullable` are\n * reflected in generated JSDoc and type modifiers.\n */\n function convertRef({ schema, nullable, defaultValue }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'ref',\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n nullable,\n description: schema.description,\n deprecated: schema.deprecated,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n pattern: schema.type === 'string' ? schema.pattern : undefined,\n example: schema.example,\n default: defaultValue,\n })\n }\n\n /**\n * Converts a `allOf` schema into either a flattened member node (single-member `allOf`)\n * or an `IntersectionSchemaNode` (multi-member `allOf`).\n *\n * Single-member `allOf` without sibling structural keys is the common OAS 3.0 pattern for\n * annotating a `$ref` or primitive with extra constraints; it is flattened to avoid\n * producing needless intersection wrappers.\n *\n * The flatten path is skipped when the outer schema carries structural keys that cannot be\n * merged into annotation fields: `properties`, `required`, or `additionalProperties`.\n * Those cases must become an intersection so the constraints are preserved.\n *\n * Circular references through discriminator parents are detected and skipped to prevent\n * infinite recursion during code generation.\n */\n function convertAllOf({ schema, name, nullable, defaultValue, options }: SchemaContext): 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 = convertSchema({ schema: memberSchema! as SchemaObject }, options)\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 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 } as DistributiveOmit<SchemaNode, 'kind'>)\n }\n\n // When a child schema extends a discriminator parent via allOf and the parent's oneOf/anyOf\n // references that child back, skip that allOf item to prevent a circular type reference.\n // When an item is skipped, collect its discriminant value so it can be injected below.\n const filteredDiscriminantValues: Array<{ propertyName: string; value: string }> = []\n const allOfMembers: Array<SchemaNode> = (schema.allOf as Array<SchemaObject | ReferenceObject>)\n .filter((item) => {\n if (!isReference(item) || !name) return true\n const deref = oas.get<SchemaObject>(item.$ref)\n if (!deref || !isDiscriminator(deref)) return true\n const parentUnion = deref.oneOf ?? deref.anyOf\n if (!parentUnion) return true\n const childRef = `#/components/schemas/${name}`\n const inOneOf = parentUnion.some((oneOfItem) => isReference(oneOfItem) && oneOfItem.$ref === childRef)\n const inMapping = Object.values(deref.discriminator.mapping ?? {}).some((v) => v === childRef)\n if (inOneOf || inMapping) {\n const discriminatorValue = Object.entries(deref.discriminator.mapping ?? {}).find(([, v]) => v === childRef)?.[0]\n if (discriminatorValue) {\n filteredDiscriminantValues.push({ propertyName: deref.discriminator.propertyName, value: discriminatorValue })\n }\n return false\n }\n return true\n })\n .map((s) => convertSchema({ schema: s as SchemaObject }, options))\n\n // Track where allOf-derived members end so each portion can be merged independently.\n const syntheticStart = allOfMembers.length\n\n // When `required` lists keys not present in the outer `properties`, resolve them from\n // the allOf member schemas and inject them as extra intersection members.\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 (!isReference(item)) return [item as SchemaObject]\n const deref = oas.get<SchemaObject>(item.$ref)\n return deref && !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(convertSchema({ schema: { properties: { [key]: resolved.properties[key] }, required: [key] } as SchemaObject }, options))\n break\n }\n }\n }\n }\n }\n\n if (schema.properties) {\n const { allOf: _allOf, ...schemaWithoutAllOf } = schema\n allOfMembers.push(convertSchema({ schema: schemaWithoutAllOf }, options))\n }\n\n // Inject a synthetic single-property object for each discriminant value collected from\n // filtered discriminator parents so that child schemas carry the narrowed literal type.\n for (const { propertyName, value } of filteredDiscriminantValues) {\n allOfMembers.push(\n createSchema({\n type: 'object',\n primitive: 'object',\n properties: [\n createProperty({\n name: propertyName,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: [value],\n }),\n required: true,\n }),\n ],\n }),\n )\n }\n\n // Merge consecutive anonymous object members within the synthetic portion — see `mergeAdjacentAnonymousObjects`.\n return createSchema({\n type: 'intersection',\n members: [...mergeAdjacentAnonymousObjects(allOfMembers.slice(0, syntheticStart)), ...mergeAdjacentAnonymousObjects(allOfMembers.slice(syntheticStart))],\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n *\n * Both keywords are treated identically — their members are concatenated into a single union.\n * When sibling `properties` are present alongside `oneOf`/`anyOf`, each union member is\n * individually intersected with the shared properties node to match the OAS pattern of\n * adding common fields next to a discriminated union.\n */\n function convertUnion({ schema, name, nullable, defaultValue, options }: SchemaContext): SchemaNode {\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n const unionBase = {\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n discriminatorPropertyName: isDiscriminator(schema) ? schema.discriminator.propertyName : undefined,\n }\n\n if (schema.properties) {\n const { oneOf: _oneOf, anyOf: _anyOf, ...schemaWithoutUnion } = schema\n const discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n\n // Strip discriminator so convertObject won't re-apply the full mapping enum.\n const memberBaseSchema: SchemaObject = discriminator\n ? (Object.fromEntries(Object.entries(schemaWithoutUnion).filter(([key]) => key !== 'discriminator')) as SchemaObject)\n : schemaWithoutUnion\n\n // Convert shared properties once to avoid duplicate enum naming\n // (e.g. StatusEnum appearing twice and getting a numeric suffix).\n const sharedPropertiesNode = convertSchema({ schema: memberBaseSchema, name }, options)\n\n return createSchema({\n type: 'union',\n ...unionBase,\n members: unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n const discriminatorValue = discriminator?.mapping && ref ? Object.entries(discriminator.mapping).find(([, v]) => v === ref)?.[0] : undefined\n\n let propertiesNode = sharedPropertiesNode\n\n if (discriminatorValue && discriminator) {\n propertiesNode = applyDiscriminatorEnum({ node: propertiesNode, propertyName: discriminator.propertyName, values: [discriminatorValue] })\n }\n\n return createSchema({\n type: 'intersection',\n members: [convertSchema({ schema: s as SchemaObject }, options), propertiesNode],\n })\n }),\n })\n }\n\n // When a discriminator with mapping is present but there are no sibling properties,\n // embed the narrowed discriminant value into each member to produce precise literal\n // intersection types (e.g. `Cat & { type: 'cat' }`) instead of plain `Cat | Dog`.\n const discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n if (discriminator?.mapping) {\n return createSchema({\n type: 'union',\n ...unionBase,\n members: unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n const discriminatorValue = ref ? Object.entries(discriminator.mapping!).find(([, v]) => v === ref)?.[0] : undefined\n const memberNode = convertSchema({ schema: s as SchemaObject }, options)\n\n if (!discriminatorValue) return memberNode\n\n const discriminantNode = createSchema({\n type: 'object',\n primitive: 'object',\n properties: [\n createProperty({\n name: discriminator.propertyName,\n schema: createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: [discriminatorValue],\n }),\n required: true,\n }),\n ],\n })\n\n return createSchema({\n type: 'intersection',\n members: [memberNode, discriminantNode],\n })\n }),\n })\n }\n\n return createSchema({\n type: 'union',\n ...unionBase,\n members: simplifyUnionMembers(unionMembers.map((s) => convertSchema({ schema: s as SchemaObject }, options))),\n })\n }\n\n /**\n * Converts an OAS 3.1 `const` schema into either a null scalar or a single-value `EnumSchemaNode`.\n * `const: null` maps to a null scalar; any other value becomes a one-item enum so that generators\n * can produce a precise literal type.\n */\n function convertConst({ schema, name, nullable, defaultValue }: SchemaContext): SchemaNode {\n const constValue = schema.const\n\n if (constValue === null) {\n // Do not propagate `nullable` here: the type is already `null`, so marking it\n // nullable too would cause the printer to emit `null | null`.\n return createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n })\n }\n\n const constPrimitive = getPrimitiveType(typeof constValue === 'number' ? 'number' : typeof constValue === 'boolean' ? 'boolean' : 'string')\n return createSchema({\n type: 'enum',\n primitive: constPrimitive,\n enumValues: [constValue as string | number | boolean],\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Handles `format`-based special types (date/time, uuid, email, blob, etc.).\n * Returns `undefined` when the format should fall through to string handling\n * (i.e. `format: 'date-time'` with `dateType: false`).\n */\n function convertFormat({ schema, name, nullable, defaultValue, mergedOptions }: SchemaContext): SchemaNode | undefined {\n const base = renderSchemaBase(schema, name, nullable, defaultValue)\n\n // int64 is option-dependent so it can't live in the static formatMap.\n if (schema.format === 'int64') {\n return createSchema({\n type: mergedOptions.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 // date-time / date / time are option-dependent and can't live in the static formatMap.\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const dateType = getDateType(mergedOptions, schema.format)\n if (!dateType) return undefined // dateType: false → fall through to string\n\n if (dateType.type === 'datetime') {\n return createSchema({ ...base, primitive: 'string' as const, type: 'datetime', offset: dateType.offset, local: dateType.local })\n }\n return createSchema({ ...base, primitive: 'string' as const, type: dateType.type, representation: dateType.representation })\n }\n\n const specialType = formatToSchemaType(schema.format!)\n if (!specialType) return undefined\n\n const specialPrimitive: PrimitiveSchemaType = specialType === 'number' || specialType === 'integer' || specialType === 'bigint' ? specialType : 'string'\n\n if (specialType === 'number' || specialType === 'integer' || specialType === 'bigint') {\n return createSchema({ ...base, primitive: specialPrimitive, type: specialType })\n }\n if (specialType === 'url') {\n return createSchema({ ...base, primitive: 'string' as const, type: 'url' })\n }\n\n return createSchema({ ...base, primitive: specialPrimitive, type: specialType as ScalarSchemaType })\n }\n\n /**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n *\n * Handles several edge cases:\n * - `{ type: 'array', enum }` (technically invalid OAS) — the enum is normalized into `items`.\n * - `null` in enum values (OAS 3.0 nullable enum convention) — stripped and reflected as `nullable`.\n * - `x-enumNames` / `x-enum-varnames` vendor extensions — produce named enum variants with explicit labels.\n * - Numeric and boolean enums require a const-map representation because most generators cannot\n * use string-enum syntax for non-string values.\n */\n function convertEnum({ schema, name, nullable, type, options }: SchemaContext): SchemaNode {\n // Malformed schema: `{ type: 'array', enum: [...] }` — normalize by moving the enum into items.\n if (type === 'array') {\n const isItemsObject = typeof schema.items === 'object' && !Array.isArray(schema.items)\n const normalizedItems: SchemaObject = { ...(isItemsObject ? (schema.items as SchemaObject) : {}), enum: schema.enum }\n const { enum: _enum, ...schemaWithoutEnum } = schema\n return convertSchema({ schema: { ...schemaWithoutEnum, items: normalizedItems } as SchemaObject, name }, options)\n }\n\n // `null` in enum values is the OAS 3.0 convention for a nullable enum.\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 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 }\n\n // x-enumNames / x-enum-varnames: named variants with explicit labels take priority.\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n if (extensionKey) {\n const rawNames = (schema as Record<string, unknown>)[extensionKey] as Array<string | number>\n const uniqueNames = [...new Set(rawNames)]\n const enumType =\n getPrimitiveType(type) === 'number' || getPrimitiveType(type) === 'integer'\n ? ('number' as const)\n : getPrimitiveType(type) === 'boolean'\n ? ('boolean' as const)\n : ('string' as const)\n\n return createSchema({\n ...enumBase,\n enumType,\n namedEnumValues: uniqueNames.map((label, index) => ({\n name: String(label),\n value: filteredValues[index] ?? label,\n format: enumType,\n })),\n })\n }\n\n // Number / integer enum — must use a const map since most generators can't use string-enum for numbers.\n if (type === 'number' || type === 'integer') {\n return createSchema({\n ...enumBase,\n enumType: 'number' as const,\n namedEnumValues: [...new Set(filteredValues)].map((value) => ({\n name: String(value),\n value: value as number,\n format: 'number' as const,\n })),\n })\n }\n\n // Boolean enum — same const-map approach as numeric.\n if (type === 'boolean') {\n return createSchema({\n ...enumBase,\n enumType: 'boolean' as const,\n namedEnumValues: [...new Set(filteredValues)].map((value) => ({\n name: String(value),\n value: value as boolean,\n format: 'boolean' as const,\n })),\n })\n }\n\n // Plain string enum (default path).\n return createSchema({\n ...enumBase,\n enumValues: [...new Set(filteredValues)],\n })\n }\n\n /**\n * Converts an object-like schema (`type: 'object'`, `properties`, `additionalProperties`,\n * or `patternProperties`) into an `ObjectSchemaNode`.\n *\n * When a `discriminator` is present, the discriminator property's schema is replaced with an\n * enum of the mapping keys so generators can produce a precise literal-union type for it.\n *\n * Property optionality follows OAS semantics:\n * - required + not nullable → `required: true`\n * - not required + not nullable → `optional: true`\n * - not required + nullable → `nullish: true`\n */\n /**\n * Builds the propagation name for a child property during recursive schema conversion.\n *\n * The parent name is prepended so the full path is encoded\n * (e.g. `OrderParams` when parent is `Order`).\n */\n function resolveChildName(parentName: string | undefined, propName: string): string | undefined {\n return parentName ? pascalCase([parentName, propName].join(' ')) : undefined\n }\n\n /**\n * Derives the final name for an enum property schema node.\n *\n * The resulting name always includes the enum suffix and full parent path context\n * (e.g. `OrderParamsStatusEnum`).\n */\n function resolveEnumPropName(parentName: string | undefined, propName: string, enumSuffix: string): string {\n return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))\n }\n\n /**\n * Given a freshly-converted property schema, returns the node with a correct\n * `name` attached — or stripped — depending on whether the node is a named\n * enum, a boolean const-enum (always inlined), or a regular schema.\n */\n function applyEnumName(propNode: SchemaNode, parentName: string | undefined, propName: string, enumSuffix: string): SchemaNode {\n const enumNode = narrowSchema(propNode, 'enum')\n\n // Boolean-primitive enum nodes (e.g. `const: false`) are always inlined as\n // literal types and must not receive a named identifier.\n if (enumNode?.primitive === 'boolean') {\n return { ...propNode, name: undefined }\n }\n\n if (enumNode) {\n return { ...propNode, name: resolveEnumPropName(parentName, propName, enumSuffix) }\n }\n\n return propNode\n }\n\n function convertObject({ schema, name, nullable, defaultValue, options, mergedOptions }: SchemaContext): SchemaNode {\n const properties: Array<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 = isNullable(resolvedPropSchema)\n\n const childName = resolveChildName(name, propName)\n const propNode = convertSchema({ schema: resolvedPropSchema, name: childName }, options)\n let schemaNode = applyEnumName(propNode, name, propName, mergedOptions.enumSuffix)\n\n const tupleNode = narrowSchema(schemaNode, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => applyEnumName(item, name, propName, mergedOptions.enumSuffix))\n if (namedItems.some((item, i) => item !== tupleNode.items![i])) {\n schemaNode = { ...tupleNode, items: namedItems }\n }\n }\n\n return 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 let additionalPropertiesNode: SchemaNode | true | undefined\n if (additionalProperties === true) {\n additionalPropertiesNode = true\n } else if (additionalProperties && Object.keys(additionalProperties).length > 0) {\n additionalPropertiesNode = convertSchema({ schema: additionalProperties as SchemaObject }, options)\n } else if (additionalProperties === false) {\n additionalPropertiesNode = undefined\n } else if (additionalProperties) {\n additionalPropertiesNode = createSchema({ type: resolveTypeOption(mergedOptions.unknownType) })\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 ? createSchema({ type: resolveTypeOption(mergedOptions.unknownType) })\n : convertSchema({ schema: patternSchema as SchemaObject }, options),\n ]),\n )\n : undefined\n\n const objectNode: SchemaNode = createSchema({\n type: 'object',\n primitive: 'object',\n properties,\n additionalProperties: additionalPropertiesNode,\n patternProperties,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n\n // When a discriminator is present, replace the discriminator property's schema\n // with an enum of the mapping keys for a precise literal-union type.\n if (isDiscriminator(schema) && schema.discriminator.mapping) {\n const discPropName = schema.discriminator.propertyName\n const values = Object.keys(schema.discriminator.mapping)\n const enumName = name ? resolveEnumPropName(name, discPropName, mergedOptions.enumSuffix) : undefined\n return applyDiscriminatorEnum({ node: objectNode, propertyName: discPropName, values, enumName })\n }\n\n return objectNode\n }\n\n /**\n * Converts an OAS 3.1 `prefixItems` tuple into a `TupleSchemaNode`.\n *\n * Each `prefixItems` element maps to a positional tuple slot. When an explicit `items` schema\n * is present alongside `prefixItems`, it becomes the rest element. When `items` is absent,\n * a rest element of type `any` is emitted to match JSON Schema semantics (absent `items`\n * means additional items are allowed).\n */\n function convertTuple({ schema, name, nullable, defaultValue, options }: SchemaContext): SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => convertSchema({ schema: item as SchemaObject }, options))\n const rest = schema.items ? convertSchema({ schema: schema.items as SchemaObject }, options) : createSchema({ type: 'any' })\n\n return createSchema({\n type: 'tuple',\n primitive: 'array',\n items: tupleItems,\n rest,\n min: schema.minItems,\n max: schema.maxItems,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'array'` schema into an `ArraySchemaNode`.\n *\n * When the items schema is an inline enum, a name derived from the parent array's name and\n * `enumSuffix` is forwarded so generators can emit a named enum declaration.\n */\n function convertArray({ schema, name, nullable, defaultValue, options, mergedOptions }: SchemaContext): SchemaNode {\n const rawItems = schema.items as SchemaObject | undefined\n // When the items schema contains an inline enum, derive a named identifier\n // so generators can emit a standalone enum declaration.\n const itemName = rawItems?.enum?.length && name ? resolveEnumPropName(undefined, name, mergedOptions.enumSuffix) : undefined\n const items = rawItems ? [convertSchema({ schema: rawItems, name: itemName }, options)] : []\n\n return createSchema({\n type: 'array',\n primitive: 'array',\n items,\n min: schema.minItems,\n max: schema.maxItems,\n unique: schema.uniqueItems ?? undefined,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'string'` schema (without a special format) into a `StringSchemaNode`.\n */\n function convertString({ schema, name, nullable, defaultValue }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'number'` or `type: 'integer'` schema into the corresponding `SchemaNode`.\n */\n function convertNumeric({ schema, name, nullable, defaultValue }: SchemaContext, type: 'number' | 'integer'): SchemaNode {\n return 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 ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'boolean'` schema into a `BooleanSchemaNode`.\n */\n function convertBoolean({ schema, name, nullable, defaultValue }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'boolean',\n primitive: 'boolean',\n ...renderSchemaBase(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts an explicit `type: 'null'` or `const: null` schema into a `NullSchemaNode`.\n */\n function convertNull({ schema, name, nullable }: SchemaContext): SchemaNode {\n return createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable,\n })\n }\n\n /**\n * Central dispatcher: converts an OAS `SchemaObject` into a `SchemaNode`.\n *\n * Dispatch order (first match wins):\n * 1. `$ref` pointer\n * 2. `allOf` composition\n * 3. `oneOf` / `anyOf` union\n * 4. `const` literal (OAS 3.1)\n * 5. `format`-based special type (date/time, uuid, blob, …)\n * 6. OAS 3.1 `contentMediaType: 'application/octet-stream'` blob\n * 7. OAS 3.1 multi-type array → union or fallthrough\n * 8. Constraint-inferred type (minLength/maxLength → string; minimum/maximum → number)\n * 9. `enum` values\n * 10. Object / array / tuple / scalar by `type`\n * 11. Empty schema fallback (`emptySchemaType` option)\n */\n function convertSchema({ schema, name }: { schema: SchemaObject; name?: string }, options?: Partial<ParserOptions>): SchemaNode {\n const mergedOptions: ParserOptions = { ...DEFAULT_PARSER_OPTIONS, ...options }\n // Flatten keyword-only allOf fragments (no $ref, no structural keys) into the parent\n // schema before parsing, so simple annotation patterns don't produce needless intersections.\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema && flattenedSchema !== schema) {\n return convertSchema({ schema: flattenedSchema, name }, options)\n }\n\n const nullable = isNullable(schema) || undefined\n const defaultValue = schema.default === null && nullable ? undefined : schema.default\n // Normalize OAS 3.1 multi-type array to a single type string for the dispatch below.\n const type = Array.isArray(schema.type) ? schema.type[0] : schema.type\n\n const ctx: SchemaContext = { schema, name, nullable, defaultValue, type, options, mergedOptions }\n\n // $ref — pointer to another definition.\n // In OAS 3.0 siblings of $ref are technically ignored, but Kubb intentionally preserves them\n // so that annotations like `pattern`, `description`, and `nullable` are reflected in generated code.\n if (isReference(schema)) return convertRef(ctx)\n\n // Composition keywords\n if (schema.allOf?.length) return convertAllOf(ctx)\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n if (unionMembers.length) return convertUnion(ctx)\n\n // OAS 3.1 const — a single fixed value, semantically equivalent to a one-item enum.\n // `const: undefined` falls through to the empty-type fallback.\n if ('const' in schema && schema.const !== undefined) return convertConst(ctx)\n\n // Format-based special types take precedence over `type`.\n // `convertFormat` returns undefined when format should fall through to string (dateType: false).\n // see https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7\n if (schema.format) {\n const formatResult = convertFormat(ctx)\n if (formatResult) return formatResult\n }\n\n // OAS 3.1: `contentMediaType: 'application/octet-stream'` on a string schema signals binary data.\n if (schema.type === 'string' && schema.contentMediaType === 'application/octet-stream') {\n return createSchema({ type: 'blob', primitive: 'string', ...renderSchemaBase(schema, name, nullable, defaultValue) })\n }\n\n // OAS 3.1: `type` may be an array — e.g. `[\"string\", \"integer\", \"null\"]`.\n // `null` in the array is the 3.1 equivalent of `nullable: true`; strip it and set the flag.\n // When 2+ non-null types remain, produce a union; when exactly 1 non-null type remains, fall through.\n if (Array.isArray(schema.type) && schema.type.length > 1) {\n const nonNullTypes = schema.type.filter((t) => t !== 'null') as string[]\n const arrayNullable = schema.type.includes('null') || nullable || undefined\n\n if (nonNullTypes.length > 1) {\n return createSchema({\n type: 'union',\n members: nonNullTypes.map((t) => convertSchema({ schema: { ...schema, type: t } as SchemaObject, name }, options)),\n ...renderSchemaBase(schema, name, arrayNullable, defaultValue),\n })\n }\n }\n\n // Infer type from constraints when no explicit type is provided.\n // minLength / maxLength / pattern → string; minimum / maximum → number.\n // Note: minItems/maxItems do NOT infer array — arrays require an `items` key.\n if (!type) {\n if (schema.minLength !== undefined || schema.maxLength !== undefined || schema.pattern !== undefined) {\n return convertString(ctx)\n }\n if (schema.minimum !== undefined || schema.maximum !== undefined) {\n return convertNumeric(ctx, 'number')\n }\n }\n\n if (schema.enum?.length) return convertEnum(ctx)\n if (type === 'object' || schema.properties || schema.additionalProperties || 'patternProperties' in schema) return convertObject(ctx)\n if ('prefixItems' in schema) return convertTuple(ctx)\n if (type === 'array' || 'items' in schema) return convertArray(ctx)\n if (type === 'string') return convertString(ctx)\n if (type === 'number') return convertNumeric(ctx, 'number')\n if (type === 'integer') return convertNumeric(ctx, 'integer')\n if (type === 'boolean') return convertBoolean(ctx)\n if (type === 'null') return convertNull(ctx)\n\n const emptyType = resolveTypeOption(mergedOptions.emptySchemaType)\n return createSchema({ type: emptyType as ScalarSchemaType, name, title: schema.title, description: schema.description })\n }\n\n /**\n * Converts a single dereferenced OAS parameter object into a `ParameterNode`.\n * When the parameter has no `schema`, falls back to `unknownType`; `$ref` schemas are resolved through `convertSchema` to produce a proper named type reference.\n */\n function parseParameter(options: ParserOptions, param: Record<string, unknown>): ParameterNode {\n const required = (param['required'] as boolean | undefined) ?? false\n\n const schema: SchemaNode = param['schema']\n ? convertSchema({ schema: param['schema'] as SchemaObject }, options)\n : createSchema({ type: resolveTypeOption(options.unknownType) })\n\n return createParameter({\n name: param['name'] as string,\n in: param['in'] as ParameterLocation,\n schema: {\n ...schema,\n description: (param['description'] as string | undefined) ?? schema.description,\n },\n required,\n })\n }\n\n /**\n * Converts an OAS `Operation` into an `OperationNode`, resolving parameters,\n * request body, and all response codes into their AST node equivalents.\n */\n function parseOperation(options: ParserOptions, oas: Oas, operation: Operation): OperationNode {\n const parameters: Array<ParameterNode> = oas.getParameters(operation).map((param) => parseParameter(options, param as unknown as Record<string, unknown>))\n\n const requestBodySchema = oas.getRequestSchema(operation)\n const requestBodySchemaNode = requestBodySchema ? convertSchema({ schema: requestBodySchema }, options) : undefined\n\n const requestBodyDescription =\n operation.schema.requestBody && !isReference(operation.schema.requestBody)\n ? (operation.schema.requestBody as { description?: string }).description\n : undefined\n\n const requestBodyKeysToOmit = requestBodySchema?.properties\n ? Object.entries(requestBodySchema.properties)\n .filter(([, prop]) => !isReference(prop) && (prop as { readOnly?: boolean }).readOnly)\n .map(([key]) => key)\n : undefined\n\n const requestBody = requestBodySchemaNode\n ? {\n description: requestBodyDescription,\n schema: requestBodySchemaNode,\n keysToOmit: requestBodyKeysToOmit?.length ? requestBodyKeysToOmit : undefined,\n }\n : undefined\n\n const responses: Array<ResponseNode> = operation.getResponseStatusCodes().map((statusCode) => {\n const responseObj = operation.getResponseByStatusCode(statusCode)\n const responseSchema = oas.getResponseSchema(operation, statusCode)\n\n const schema =\n responseSchema && Object.keys(responseSchema).length > 0\n ? convertSchema({ schema: responseSchema }, options)\n : createSchema({ type: resolveTypeOption(options.emptySchemaType) })\n\n const description = typeof responseObj === 'object' && responseObj !== null && !Array.isArray(responseObj) ? responseObj.description : undefined\n\n const rawContent =\n typeof responseObj === 'object' && responseObj !== null && !Array.isArray(responseObj)\n ? (responseObj as { content?: Record<string, unknown> }).content\n : undefined\n\n const mediaType = rawContent ? toMediaType(Object.keys(rawContent)[0] ?? '') : toMediaType(operation.contentType ?? '')\n\n const keysToOmit = responseSchema?.properties\n ? Object.entries(responseSchema.properties)\n .filter(([, prop]) => !isReference(prop) && (prop as { writeOnly?: boolean }).writeOnly)\n .map(([key]) => key)\n : undefined\n\n return createResponse({\n statusCode: statusCode as StatusCode,\n description,\n schema,\n mediaType,\n keysToOmit: keysToOmit?.length ? keysToOmit : undefined,\n })\n })\n\n return createOperation({\n operationId: operation.getOperationId(),\n method: operation.method.toUpperCase() as HttpMethod,\n path: new URLPath(operation.path).URL,\n tags: operation.getTags().map((tag) => tag.name),\n summary: operation.getSummary() || undefined,\n description: operation.getDescription() || undefined,\n deprecated: operation.isDeprecated() || undefined,\n parameters,\n requestBody,\n responses,\n })\n }\n\n /**\n * Converts an OpenAPI/Swagger spec (wrapped in a Kubb `Oas` instance) into\n * a `RootNode` — the top-level node of the `@kubb/ast` tree.\n */\n function parse<TOptions extends Partial<ParserOptions> = object>(options?: TOptions): RootNode {\n const mergedOptions: ParserOptions = { ...DEFAULT_PARSER_OPTIONS, ...options }\n\n const schemas: Array<SchemaNode> = Object.entries(schemaObjects).map(([name, schemaObject]) =>\n convertSchema({ schema: schemaObject as SchemaObject, name }, mergedOptions),\n )\n\n const paths = oas.getPaths()\n\n const operations: Array<OperationNode> = Object.entries(paths).flatMap(([_path, methods]) =>\n Object.entries(methods)\n .map(([, operation]) => (operation ? parseOperation(mergedOptions, oas, operation) : null))\n .filter((op): op is OperationNode => op !== null),\n )\n\n return createRoot({ schemas, operations })\n }\n\n /**\n * Walks a `SchemaNode` tree and resolves all `ref` node names through the provided callbacks.\n *\n * `resolveName` handles all schema types; `resolveEnumName` (when provided) takes precedence\n * for `enum` nodes, enabling a separate naming strategy for enums (e.g. different suffix).\n *\n * Collision-resolved names (from `nameMapping`) are applied before user-supplied resolvers.\n */\n function resolveRefs(node: SchemaNode, resolveName: (ref: string) => string | undefined, resolveEnumName?: (name: string) => string | undefined): SchemaNode {\n return transform(node, {\n schema(schemaNode) {\n const schemaRef = narrowSchema(schemaNode, schemaTypes.ref)\n\n if (schemaRef && (schemaRef.ref || schemaRef.name)) {\n const rawRef = schemaRef.ref ?? schemaRef.name!\n const resolved = resolveName(nameMapping.get(rawRef) ?? rawRef)\n if (resolved) {\n return { ...schemaNode, name: resolved }\n }\n }\n\n if (schemaNode.type === 'enum' && schemaNode.name) {\n const resolved = (resolveEnumName ?? resolveName)(schemaNode.name)\n if (resolved) {\n return { ...schemaNode, name: resolved }\n }\n }\n },\n }) as SchemaNode\n }\n\n return {\n parse,\n convertSchema,\n resolveRefs,\n nameMapping,\n } as OasParser\n}\n","import path from 'node:path'\nimport { createRoot } from '@kubb/ast'\nimport type { AdapterSource } from '@kubb/core'\nimport { createAdapter } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { resolveServerUrl } from './oas/resolveServerUrl.ts'\nimport { parseFromConfig } from './oas/utils.ts'\nimport { createOasParser } from './parser.ts'\nimport type { OasAdapter } from './types.ts'\nimport { getImports } from './utils.ts'\n\nexport const adapterOasName = 'oas' satisfies OasAdapter['name']\n\n/**\n * Creates an OpenAPI / Swagger adapter for Kubb.\n *\n * This is the default adapter — you can omit it from your config when using\n * an OpenAPI spec, but supplying it explicitly lets you pass options.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n *\n * export default defineConfig({\n * adapter: adapterOas({ validate: true, dateType: 'date' }),\n * input: { path: './openapi.yaml' },\n * plugins: [pluginTs(), pluginZod()],\n * })\n * ```\n */\nexport const adapterOas = createAdapter<OasAdapter>((options) => {\n const {\n validate = true,\n oasClass,\n contentType,\n serverIndex,\n serverVariables,\n discriminator = 'strict',\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 // Mutable Map shared between `options` and each `parse()` call.\n // Populated (and replaced) on every parse so consumers always see the latest state.\n const nameMapping = new Map<string, string>()\n\n return {\n name: adapterOasName,\n options: {\n validate,\n oasClass,\n contentType,\n serverIndex,\n serverVariables,\n discriminator,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n nameMapping,\n },\n getImports(node, resolve) {\n return getImports({ node, nameMapping, resolve })\n },\n async parse(source) {\n const fakeConfig = sourceToFakeConfig(source)\n const oas = await parseFromConfig(fakeConfig, oasClass)\n\n oas.setOptions({ contentType, discriminator })\n\n if (validate) {\n try {\n await oas.validate()\n } catch (_err) {\n // Validation failures are non-fatal — mirror plugin-oas behavior\n }\n }\n\n const server = serverIndex !== undefined ? oas.api.servers?.at(serverIndex) : undefined\n const baseURL = server?.url ? resolveServerUrl(server, serverVariables) : undefined\n\n const parser = createOasParser(oas, { contentType })\n const root = parser.parse({ dateType, integerType, unknownType, emptySchemaType, enumSuffix })\n\n // This must happen after parse() because legacy enum remapping is finalized there.\n nameMapping.clear()\n for (const [key, value] of parser.nameMapping) {\n nameMapping.set(key, value)\n }\n\n return createRoot({\n ...root,\n meta: {\n title: oas.api.info?.title,\n description: oas.api.info?.description,\n version: oas.api.info?.version,\n baseURL,\n },\n })\n },\n }\n})\n\n// TODO: remove once parseFromConfig accepts AdapterSource directly\nfunction sourceToFakeConfig(source: AdapterSource): Parameters<typeof parseFromConfig>[0] {\n switch (source.type) {\n case 'path':\n return { root: path.dirname(source.path), input: { path: source.path } } as Parameters<typeof parseFromConfig>[0]\n case 'data':\n return { root: process.cwd(), input: { data: source.data } } as Parameters<typeof parseFromConfig>[0]\n case 'paths':\n return {\n root: source.paths[0] ? path.dirname(source.paths[0]) : process.cwd(),\n input: source.paths.map((p) => ({ path: p })),\n } as Parameters<typeof parseFromConfig>[0]\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;CACb,aA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