{"version":3,"file":"index.mjs","names":["isNullSchema","modelShapeKey","isRecord","sameNames","isNullSchema","isRecord","isRecord","fingerprintType"],"sources":["../src/ir/sdk-behavior.ts","../src/parser/refs.ts","../src/parser/external-docs.ts","../src/parser/extensions.ts","../src/parser/enum-members.ts","../src/parser/union-shape.ts","../src/parser/inline-models.ts","../src/parser/schemas.ts","../src/parser/pagination.ts","../src/parser/materialize-inline.ts","../src/parser/responses.ts","../src/parser/path-item-refs.ts","../src/parser/reference-objects.ts","../src/parser/response-refs.ts","../src/parser/security.ts","../src/parser/servers.ts","../src/parser/envelope-companion-names.ts","../src/parser/callbacks.ts","../src/parser/operations.ts","../src/parser/webhooks.ts","../src/parser/normalize-inline-models.ts","../src/parser/collect-inline-enums.ts","../src/parser/parameter-group-names.ts","../src/parser/normalize-model-refs.ts","../src/parser/collapse-error-bodies.ts","../src/parser/parse.ts","../src/engine/operation-plan.ts","../src/utils/escape.ts","../src/snippets/example-builder.ts","../src/snippets/runner.ts","../src/snippets/shared.ts"],"sourcesContent":["/**\n * SDK Behavior IR — language-agnostic runtime policies for generated SDKs.\n *\n * These types capture the \"what\" of SDK behavior (retry, telemetry, errors, etc.)\n * while emitters provide the \"how\" (language-specific mechanism).\n *\n * Emitters access these via `ctx.spec.sdk` — always populated, never undefined.\n */\n\n// ── Retry ──────────────────────────────────────────────────────────\n\n/** Retry policy — when and how to retry failed requests. */\nexport interface RetryPolicy {\n  /** HTTP status codes that trigger a retry. */\n  retryableStatusCodes: number[];\n  /** Maximum number of retry attempts (0 = no retries). */\n  maxRetries: number;\n  /** Whether to retry on connection errors (DNS failure, TCP reset). */\n  retryOnConnectionError: boolean;\n  /** Whether to retry on timeout errors. */\n  retryOnTimeout: boolean;\n  /** Backoff strategy between retries. */\n  backoff: BackoffStrategy;\n}\n\n/** Exponential backoff configuration.\n *\n * Formula: `delay = min(initialDelay * multiplier^attempt, maxDelay)`\n * With jitter: `delay += delay * jitterFactor * random(0, 1)`\n */\nexport interface BackoffStrategy {\n  /** Initial delay in seconds before the first retry. */\n  initialDelay: number;\n  /** Multiplier applied to the delay on each subsequent retry. */\n  multiplier: number;\n  /** Maximum delay in seconds (cap). */\n  maxDelay: number;\n  /** Jitter factor (0..1). 0.5 means up to 50% random jitter added. */\n  jitterFactor: number;\n}\n\n// ── Errors ─────────────────────────────────────────────────────────\n\n/** Error mapping — status codes to named exception kinds. */\nexport interface ErrorPolicy {\n  /** Map from HTTP status code to a logical error kind name (e.g. 400 → 'BadRequest').\n   *  Emitters append language-specific suffixes (e.g. 'BadRequestException'). */\n  statusCodeMap: Record<number, string>;\n  /** Catch-all error kind for 5xx status codes not in the map. */\n  serverErrorKind: string;\n  /** Catch-all error kind for unrecognized status codes. */\n  clientErrorKind: string;\n  /** URL template for error documentation. Use {code} as placeholder for the API error code. */\n  errorDocUrlTemplate?: string;\n}\n\n// ── Telemetry ──────────────────────────────────────────────────────\n\n/** Telemetry — what request metrics to track and send. */\nexport interface TelemetryPolicy {\n  /** Whether telemetry is enabled by default. Users can opt out via constructor param. */\n  enabledByDefault: boolean;\n  /** Header name for client telemetry data (previous request's ID + latency). */\n  headerName: string;\n  /** Response header name for the request ID. */\n  requestIdHeader: string;\n}\n\n// ── Pagination ─────────────────────────────────────────────────────\n\n/** Pagination behavior defaults. */\nexport interface PaginationPolicy {\n  /** Delay in milliseconds between pages during auto-pagination. 0 = no delay. */\n  autoPageDelayMs: number;\n}\n\n// ── Idempotency ────────────────────────────────────────────────────\n\n/** Idempotency auto-generation rules. */\nexport interface IdempotencyPolicy {\n  /** Header name for the idempotency key. */\n  headerName: string;\n  /** Whether to auto-generate a UUID v4 idempotency key for POST requests when retries > 0. */\n  autoGenerateForPost: boolean;\n}\n\n// ── Logging ────────────────────────────────────────────────────────\n\n/** Logging contract — what to log at which level. */\nexport interface LoggingPolicy {\n  /** Whether structured logging hooks are generated. */\n  enabled: boolean;\n  /** Log events that the generated client emits. */\n  events: LogEvent[];\n}\n\n/** A discrete loggable event in the request lifecycle. */\nexport type LogEvent =\n  | 'request.start'\n  | 'request.success'\n  | 'request.retry'\n  | 'request.rate_limited'\n  | 'request.error'\n  | 'request.connection_error';\n\n// ── User-Agent ─────────────────────────────────────────────────────\n\n/** User-Agent construction rules. */\nexport interface UserAgentPolicy {\n  /** Template for the SDK identifier string.\n   *  Placeholders: {name} = spec name, {lang} = emitter language, {version} = SDK version.\n   *  Each emitter interpolates with its own language string and casing conventions.\n   *  Example: '{name} {lang}/{version}' → 'Acme PHP/4.32.0' */\n  sdkIdentifierTemplate: string;\n  /** Whether to append the runtime/language version (e.g. PHP 8.2, Python 3.12). */\n  includeRuntimeVersion: boolean;\n  /** Whether to allow app info enrichment via setAppInfo(name, version, url). */\n  allowAppInfo: boolean;\n  /** AI agent environment variable detection entries. */\n  aiAgentEnvVars: AiAgentEnvVar[];\n}\n\n/** Maps an environment variable to an AI agent slug for User-Agent enrichment. */\nexport interface AiAgentEnvVar {\n  /** Environment variable to check (e.g. 'CLAUDE_CODE'). */\n  envVar: string;\n  /** Agent name to append to User-Agent (e.g. 'ClaudeCode'). */\n  agentName: string;\n}\n\n// ── Request Guards ─────────────────────────────────────────────────\n\n/** Guards that validate request params before sending. */\nexport interface RequestGuardPolicy {\n  /** Keys that should be in RequestOptions, not in params.\n   *  If detected in the body or query params, the SDK throws an error. */\n  optionKeys: string[];\n}\n\n// ── Timeouts ───────────────────────────────────────────────────────\n\n/** Timeout configuration. */\nexport interface TimeoutPolicy {\n  /** Default HTTP request timeout in seconds. */\n  defaultTimeoutSeconds: number;\n  /** Environment variable name to override the timeout (e.g. 'SDK_REQUEST_TIMEOUT'). */\n  timeoutEnvVar?: string;\n}\n\n// ── Root ───────────────────────────────────────────────────────────\n\n/** Language-agnostic runtime policies for generated SDKs.\n *  Attached to `ApiSpec.sdk` and consumed by emitters via `ctx.spec.sdk`. */\nexport interface SdkBehavior {\n  retry: RetryPolicy;\n  errors: ErrorPolicy;\n  telemetry: TelemetryPolicy;\n  pagination: PaginationPolicy;\n  idempotency: IdempotencyPolicy;\n  logging: LoggingPolicy;\n  userAgent: UserAgentPolicy;\n  requestGuard: RequestGuardPolicy;\n  timeout: TimeoutPolicy;\n}\n\n// ── Defaults ───────────────────────────────────────────────────────\n\n/**\n * Canonical SDK behavior defaults. Per-language or per-project overrides can\n * be applied via `mergeSdkBehavior()` in each SDK's `oagen.config.ts`.\n *\n * - Retry: exponential backoff with jitter, retries on 429/5xx\n * - Errors: standard HTTP status → exception kind mapping\n * - Telemetry: enabled by default, tracks request ID + latency\n * - Pagination: no inter-page delay (Node overrides to 350ms)\n * - Idempotency: auto-generate UUID v4 for retryable POSTs\n * - Logging: all lifecycle events enabled\n * - User-Agent: SDK identifier + runtime version + app info + AI agent detection\n * - Request guards: detect misplaced RequestOptions keys in params\n * - Timeout: 60s default (Python overrides to 30s)\n */\nexport function defaultSdkBehavior(): SdkBehavior {\n  return {\n    retry: {\n      retryableStatusCodes: [429, 500, 502, 503, 504],\n      maxRetries: 3,\n      retryOnConnectionError: true,\n      retryOnTimeout: true,\n      backoff: {\n        initialDelay: 1.0,\n        multiplier: 2.0,\n        maxDelay: 30.0,\n        jitterFactor: 0.5,\n      },\n    },\n    errors: {\n      statusCodeMap: {\n        400: 'BadRequest',\n        401: 'Authentication',\n        403: 'Authorization',\n        404: 'NotFound',\n        409: 'Conflict',\n        422: 'UnprocessableEntity',\n        429: 'RateLimitExceeded',\n      },\n      serverErrorKind: 'Server',\n      clientErrorKind: 'Api',\n    },\n    telemetry: {\n      enabledByDefault: true,\n      headerName: 'X-Client-Telemetry',\n      requestIdHeader: 'X-Request-ID',\n    },\n    pagination: {\n      autoPageDelayMs: 0,\n    },\n    idempotency: {\n      headerName: 'Idempotency-Key',\n      autoGenerateForPost: true,\n    },\n    logging: {\n      enabled: true,\n      events: [\n        'request.start',\n        'request.success',\n        'request.retry',\n        'request.rate_limited',\n        'request.error',\n        'request.connection_error',\n      ],\n    },\n    userAgent: {\n      sdkIdentifierTemplate: '{name} {lang}/{version}',\n      includeRuntimeVersion: true,\n      allowAppInfo: true,\n      aiAgentEnvVars: [\n        { envVar: 'CLAUDE_CODE', agentName: 'ClaudeCode' },\n        { envVar: 'CURSOR_AGENT', agentName: 'Cursor' },\n        { envVar: 'CLINE_ACTIVE', agentName: 'Cline' },\n        { envVar: 'WINDSURF_ACTIVE', agentName: 'Windsurf' },\n        { envVar: 'COPILOT_AGENT', agentName: 'Copilot' },\n      ],\n    },\n    requestGuard: {\n      optionKeys: [\n        'api_key',\n        'apiKey',\n        'idempotency_key',\n        'idempotencyKey',\n        'extra_headers',\n        'extraHeaders',\n        'max_retries',\n        'maxRetries',\n        'base_url',\n        'baseUrl',\n      ],\n    },\n    timeout: {\n      defaultTimeoutSeconds: 60,\n    },\n  };\n}\n\n// ── Merge ──────────────────────────────────────────────────────────\n\n/** Recursive partial type for deep overrides. */\nexport type DeepPartial<T> = {\n  [K in keyof T]?: T[K] extends (infer U)[]\n    ? U[] // Arrays replace entirely (don't concat)\n    : T[K] extends object\n      ? DeepPartial<T[K]>\n      : T[K];\n};\n\n/**\n * Deep-merge partial overrides into the canonical defaults.\n * Arrays replace entirely (so `retryableStatusCodes: [429]` replaces the full list,\n * rather than appending). Object properties are merged recursively.\n */\nexport function mergeSdkBehavior(overrides: DeepPartial<SdkBehavior>): SdkBehavior {\n  return deepMerge(\n    defaultSdkBehavior() as unknown as Record<string, unknown>,\n    overrides as unknown as Record<string, unknown>,\n  ) as unknown as SdkBehavior;\n}\n\n/**\n * Self-contained deep merge (no external imports — ir/ is layer 0).\n * Arrays and primitives from `source` replace those in `target`.\n * Objects are merged recursively.\n */\nfunction deepMerge(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> {\n  const result: Record<string, unknown> = { ...target };\n  for (const key of Object.keys(source)) {\n    const sourceVal = source[key];\n    const targetVal = target[key];\n    if (sourceVal === undefined) continue;\n    if (\n      sourceVal !== null &&\n      typeof sourceVal === 'object' &&\n      !Array.isArray(sourceVal) &&\n      targetVal !== null &&\n      typeof targetVal === 'object' &&\n      !Array.isArray(targetVal)\n    ) {\n      result[key] = deepMerge(targetVal as Record<string, unknown>, sourceVal as Record<string, unknown>);\n    } else {\n      result[key] = sourceVal;\n    }\n  }\n  return result;\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { makeDocumentFromString, bundleDocument, createConfig, BaseResolver, Oas3_1Types } from '@redocly/openapi-core';\nimport { SpecParseError } from '../errors.js';\n\nexport interface BundledSpec {\n  parsed: Record<string, unknown>;\n  specPath: string;\n}\n\nexport async function loadAndBundleSpec(specPath: string): Promise<BundledSpec> {\n  const absolutePath = resolve(specPath);\n  const content = await readFile(absolutePath, 'utf-8');\n  const document = makeDocumentFromString(content, pathToFileURL(absolutePath).href);\n\n  const config = await createConfig({});\n  const resolver = new BaseResolver();\n\n  const result = await bundleDocument({\n    document,\n    config,\n    types: Oas3_1Types,\n    externalRefResolver: resolver,\n    dereference: false,\n  });\n\n  if (result.problems.some((p) => p.severity === 'error')) {\n    const errors = result.problems\n      .filter((p) => p.severity === 'error')\n      .map((p) => p.message)\n      .join('\\n');\n    throw new SpecParseError(\n      `Failed to parse spec: ${errors}`,\n      `Check the OpenAPI spec at \"${absolutePath}\" for syntax errors. Run a linter such as \\`npx @redocly/cli lint ${specPath}\\` to identify issues.`,\n    );\n  }\n\n  return {\n    parsed: result.bundle.parsed as Record<string, unknown>,\n    specPath: absolutePath,\n  };\n}\n","import type { ExternalDocs } from '../ir/types.js';\n\n/**\n * An External Documentation Object as written in the OpenAPI document, before\n * validation. Any key may be missing or of the wrong type; `readExternalDocs`\n * decides what reaches the IR.\n */\nexport interface RawExternalDocs {\n  url?: string;\n  description?: string;\n}\n\n/**\n * Read an `externalDocs` value from the document into the IR.\n *\n * Only `url` makes the object meaningful, so an entry is kept when `url` is a\n * string with non-whitespace content and dropped otherwise — a non-object, a\n * missing `url`, a blank one. The parser ignored `externalDocs` entirely\n * before it was read, so a malformed value must keep parsing the way a\n * malformed document tag does: it is skipped, neither warned about nor thrown\n * on, and nothing the IR used to carry is lost.\n *\n * `url` is kept exactly as written. OpenAPI allows it to be relative to the\n * document's own location, which the parser does not know, so it neither\n * resolves nor rewrites it. `description` is carried only when it has\n * non-whitespace content, matching how a blank operation summary or tag\n * description is treated as absent; text with content is kept verbatim.\n */\nexport function readExternalDocs(raw: unknown): ExternalDocs | undefined {\n  if (typeof raw !== 'object' || raw === null) return undefined;\n  const { url, description } = raw as RawExternalDocs;\n  if (typeof url !== 'string' || url.trim() === '') return undefined;\n  const described = typeof description === 'string' && description.trim() !== '';\n  return described ? { url, description } : { url };\n}\n\n/**\n * `{ externalDocs }` when `raw` is a usable entry and `{}` otherwise, for\n * spreading into an IR node literal so the key stays absent — not present but\n * `undefined` — on nodes without one. Same shape as `constraintsEntry`.\n */\nexport function externalDocsEntry(raw: unknown): { externalDocs?: ExternalDocs } {\n  const externalDocs = readExternalDocs(raw);\n  return externalDocs ? { externalDocs } : {};\n}\n","import type { Extensions } from '../ir/types.js';\nimport type { SchemaObject } from './schemas.js';\n\n/**\n * The Schema Object extensions the parser reads into typed IR fields, so\n * they are not repeated in a model's, field's or enum's `extensions`:\n * `x-enum-descriptions` / `x-enumDescriptions` give each enum value its\n * `description` (`enumValueDescriptions` in `schemas.ts`).\n */\nexport const SCHEMA_CONSUMED_EXTENSIONS: ReadonlySet<string> = new Set(['x-enum-descriptions', 'x-enumDescriptions']);\n\n/**\n * The Operation Object extensions the parser reads into typed fields, so\n * they are not repeated in an operation's `extensions`: `x-pagination`\n * (`pagination`, through `resolvePaginationOverride`), `x-oagen-async`\n * (`async`), `x-mutually-exclusive-parameter-groups` and\n * `x-mutually-exclusive-body-groups` (`parameterGroups`).\n */\nexport const OPERATION_CONSUMED_EXTENSIONS: ReadonlySet<string> = new Set([\n  'x-pagination',\n  'x-oagen-async',\n  'x-mutually-exclusive-parameter-groups',\n  'x-mutually-exclusive-body-groups',\n]);\n\nconst NONE_CONSUMED: ReadonlySet<string> = new Set();\n\n/**\n * The specification extensions `source` declares — every own key that\n * starts with `x-`, in document order, each with its value exactly as\n * written (an object or array value is the document's own, not a copy) —\n * less the keys in `consumed`, which the parser reads into typed fields\n * elsewhere. `undefined` when none remains, so an IR node built from the\n * result has no `extensions` key at all rather than an empty object.\n */\nexport function extensionsOf(source: object, consumed: ReadonlySet<string> = NONE_CONSUMED): Extensions | undefined {\n  let out: Extensions | undefined;\n  for (const [key, value] of Object.entries(source)) {\n    if (!key.startsWith('x-') || consumed.has(key)) continue;\n    (out ??= {})[key] = value;\n  }\n  return out;\n}\n\n/**\n * `{ extensions }` when a Schema Object declares at least one extension the\n * parser does not consume (`SCHEMA_CONSUMED_EXTENSIONS`), `{}` otherwise —\n * spread into a `Model`, `Field` or `Enum` literal so the key stays absent\n * rather than present-but-undefined, as `constraintsEntry` and\n * `deprecatedEntry` are.\n */\nexport function schemaExtensionsEntry(schema: SchemaObject): { extensions?: Extensions } {\n  const extensions = extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS);\n  return extensions ? { extensions } : {};\n}\n\n/**\n * `{ extensions }` when an Operation Object declares at least one extension\n * the parser does not consume (`OPERATION_CONSUMED_EXTENSIONS`), `{}`\n * otherwise — spread into the `Operation` literal.\n */\nexport function operationExtensionsEntry(op: object): { extensions?: Extensions } {\n  const extensions = extensionsOf(op, OPERATION_CONSUMED_EXTENSIONS);\n  return extensions ? { extensions } : {};\n}\n","import type { EnumRef, EnumValue, Extensions, ExternalDocs, TypeRef } from '../ir/types.js';\nimport { assertNever } from '../ir/types.js';\nimport { toUpperSnakeCase } from '../utils/naming.js';\nimport { readExternalDocs } from './external-docs.js';\n\n/**\n * One member of an enum as the document declares it: the value, and the\n * documentation the document can attach to that one value — a `description`\n * (from the member's own `const` schema or an `x-enum-descriptions` /\n * `x-enumDescriptions` entry) and `deprecated: true` (from a `const` member\n * only; a plain `enum:` list has no per-value keyword). `enumMembersOf` in\n * `schemas.ts` reads them; `toEnumValue` turns one into the IR's `EnumValue`.\n */\nexport interface EnumMember {\n  value: string | number;\n  description?: string;\n  /** Only ever `true`; the key is absent otherwise, as on every IR node. */\n  deprecated?: boolean;\n}\n\n/**\n * What an inline enum ref carries besides its `values`, for the pass that\n * lifts it to a top-level `Enum`: each member's documentation, and the\n * `description` and link its schema declared. A side table rather than keys\n * on the ref: the ref is the field's or parameter's *type*, which the\n * sameness passes compare by serialization, and documentation is not shape\n * — it sits beside the type on the `Field`, not inside it. Per-value\n * deprecation is shape, though, so every pass that serializes a ref to\n * compare shapes reads it back through `shapeWithEnumFlags`. Keyed by\n * identity because every pass between building a ref and lifting it mutates\n * refs in place (renames, nullable wraps) and none clones them; an\n * unreachable ref drops out on its own.\n */\ninterface InlineEnumMeta {\n  members: EnumMember[];\n  description?: string;\n  externalDocs?: ExternalDocs;\n  /** The schema's own `x-*` keys, less the consumed ones (`extensionsOf`), read like its link. */\n  extensions?: Extensions;\n}\n\nconst inlineEnumMeta = new WeakMap<EnumRef, InlineEnumMeta>();\n\n/** `raw` when it is a string with non-whitespace content, kept verbatim; `undefined` otherwise. */\nfunction textWithContent(raw: unknown): string | undefined {\n  return typeof raw === 'string' && raw.trim() !== '' ? raw : undefined;\n}\n\n/**\n * Build an inline `EnumRef` from its members, recording for the lift pass\n * their documentation and what the schema declares for the enum as a whole:\n * its `description` (`rawDescription`, kept when it is a string with\n * non-whitespace content, as `Model.description` is) and its link\n * (`rawExternalDocs`, when usable). The schema is the one that declares the\n * members — the `enum:` list or the `oneOf`/`anyOf` of consts — as the\n * caller hands it over: `schemaToTypeRef` passes a collapsed nullable or\n * single-member `allOf` wrapper's text and link onto its branch first\n * (`withWrapperDocs`), so both are read by one rule.\n */\nexport function inlineEnumRef(\n  name: string,\n  members: readonly EnumMember[],\n  rawExternalDocs: unknown,\n  rawDescription?: unknown,\n  extensions?: Extensions,\n): EnumRef {\n  const ref: EnumRef = { kind: 'enum', name, values: members.map((member) => member.value) };\n  const description = textWithContent(rawDescription);\n  const externalDocs = readExternalDocs(rawExternalDocs);\n  inlineEnumMeta.set(ref, {\n    members: [...members],\n    ...(description !== undefined ? { description } : {}),\n    ...(externalDocs ? { externalDocs } : {}),\n    // The schema's extensions, already read by the caller (`extensionsOf`,\n    // the consumed keys left out), so the lifted enum carries them as it\n    // carries the link.\n    ...(extensions ? { extensions } : {}),\n  });\n  return ref;\n}\n\n/** The `description` recorded for an inline enum ref by `inlineEnumRef`; none for a ref built any other way, or from a schema whose text has no content. */\nexport function inlineEnumDescriptionOf(ref: EnumRef): string | undefined {\n  return inlineEnumMeta.get(ref)?.description;\n}\n\n/** The link recorded for an inline enum ref by `inlineEnumRef`; none for a ref built any other way. */\nexport function inlineEnumExternalDocsOf(ref: EnumRef): ExternalDocs | undefined {\n  return inlineEnumMeta.get(ref)?.externalDocs;\n}\n\n/** The extensions recorded for an inline enum ref by `inlineEnumRef`; none for a ref built any other way, or from a schema that declares none. */\nexport function inlineEnumExtensionsOf(ref: EnumRef): Extensions | undefined {\n  return inlineEnumMeta.get(ref)?.extensions;\n}\n\n/** Give `to`, a copy of `from`, the members, description and link recorded for `from`: a copy made any other way is a bare name to every pass that reads them (`cloneTypeRef`). */\nexport function copyInlineEnumMeta(from: EnumRef, to: EnumRef): void {\n  const meta = inlineEnumMeta.get(from);\n  if (meta) inlineEnumMeta.set(to, { ...meta, members: [...meta.members] });\n}\n\n/** The IR's `EnumValue` for one member: the display name is the value's UPPER_SNAKE_CASE form; `description` and `deprecated` only when the member carries them. */\nexport function toEnumValue(member: EnumMember): EnumValue {\n  return {\n    name: toUpperSnakeCase(String(member.value)),\n    value: member.value,\n    ...(member.description !== undefined ? { description: member.description } : {}),\n    ...(member.deprecated === true ? { deprecated: true } : {}),\n  };\n}\n\n/**\n * The `EnumValue`s an inline enum ref lifts to: one per entry of its\n * `values`, in that order, each with the documentation `inlineEnumRef`\n * recorded for that position — by occurrence, not by value, so a repeated\n * `const` branch keeps its own description and flag, as the same schema under\n * `components.schemas` does. Should a ref's `values` no longer match the\n * recorded members one for one (nothing in the parser edits them), each\n * value takes the first member recorded for it. A ref built without\n * `inlineEnumRef` (a test's, a plugin's) lifts to bare values; a ref without\n * `values` (a component's) lifts to none.\n */\nexport function enumValuesOf(ref: EnumRef): EnumValue[] {\n  const values = ref.values ?? [];\n  const members = inlineEnumMeta.get(ref)?.members ?? [];\n  const aligned = members.length === values.length && members.every((member, i) => member.value === values[i]);\n  if (aligned) return members.map(toEnumValue);\n  const first = new Map<string | number, EnumMember>();\n  for (const member of members) if (!first.has(member.value)) first.set(member.value, member);\n  return values.map((value) => toEnumValue(first.get(value) ?? { value }));\n}\n\n/**\n * The shape of one enum member, as a JSON text so no two members read alike:\n * `[value, deprecated]`, the value with its primitive type (the IR keeps\n * numeric `5` and string `\"5\"` distinct, and so do the emitters) and the flag\n * as a boolean — a live `\"active!deprecated\"` and a deprecated `\"active\"` are\n * `[\"active!deprecated\",false]` and `[\"active\",true]`. Two inline enums with\n * the same values are shared under one name only when they also deprecate\n * the same ones, so a field whose schema does not deprecate a value never\n * resolves to an enum that marks it. `description` is documentation, not\n * shape, and does not count — a value's, and the enum's own alike: the first\n * lifted copy's text wins, as its link does.\n */\nexport function enumValueShapeKey(value: Pick<EnumValue, 'value' | 'deprecated'>): string {\n  return JSON.stringify([value.value, value.deprecated === true]);\n}\n\n/**\n * The shape of a whole member list, order-insensitive: the sorted\n * `enumValueShapeKey`s as one JSON array text, so a fingerprint that embeds\n * it cannot read one list as another.\n */\nexport function enumShapeKey(values: readonly Pick<EnumValue, 'value' | 'deprecated'>[]): string {\n  return `[${values.map(enumValueShapeKey).sort().join(',')}]`;\n}\n\n/**\n * Order-insensitive: a reordering of the same members (`enumValueShapeKey`)\n * is the same type. Compared as complete sorted lists (`enumShapeKey`), not\n * as sets, so a repeated member counts each time it occurs: `[a, a!, b]`\n * and `[a, a, b]` are different types, and the second never shares the\n * first's deprecation.\n */\nexport function sameEnumShape(\n  a: readonly Pick<EnumValue, 'value' | 'deprecated'>[],\n  b: readonly Pick<EnumValue, 'value' | 'deprecated'>[],\n): boolean {\n  return enumShapeKey(a) === enumShapeKey(b);\n}\n\n/**\n * `ref` as a plain value for shape comparison: the same tree, with each\n * inline enum ref's deprecated values spelled out beside its `values`\n * (`deprecatedValues`, in `values` order, present only when there is one),\n * so a pass that serializes types to decide whether two models are one shape\n * — `modelFingerprint`, the merge passes' field and variant signatures, the\n * named-union shape key — sees what the side table holds, and two shapes\n * that differ only in a member's deprecation never serialize alike.\n * Descriptions are documentation and are not added. The result is not a\n * `TypeRef`: it is only ever serialized, never handed back to the IR.\n */\nexport function shapeWithEnumFlags(ref: TypeRef): unknown {\n  switch (ref.kind) {\n    case 'primitive':\n    case 'literal':\n    case 'model':\n      return ref;\n    case 'enum': {\n      if (!ref.values) return ref;\n      const deprecatedValues = enumValuesOf(ref)\n        .filter((value) => value.deprecated === true)\n        .map((value) => value.value);\n      return deprecatedValues.length > 0 ? { ...ref, deprecatedValues } : ref;\n    }\n    case 'array':\n      return { ...ref, items: shapeWithEnumFlags(ref.items) };\n    case 'nullable':\n      return { ...ref, inner: shapeWithEnumFlags(ref.inner) };\n    case 'map':\n      return {\n        ...ref,\n        valueType: shapeWithEnumFlags(ref.valueType),\n        ...(ref.keyType ? { keyType: shapeWithEnumFlags(ref.keyType) } : {}),\n      };\n    case 'union':\n      return { ...ref, variants: ref.variants.map(shapeWithEnumFlags) };\n    default:\n      return assertNever(ref);\n  }\n}\n","import type { Model, TypeRef } from '../ir/types.js';\n\n/** A model's dispatch rules: the discriminator property and the mapping from each value to a variant model name. */\nexport type Discriminator = NonNullable<Model['discriminator']>;\n\n/**\n * The part of a model's shape its named-union metadata contributes to a\n * structural fingerprint: `''` for a model that is no union, else its\n * variants — each through `variantKey`, in document order or sorted when the\n * caller treats member order as irrelevant, the list JSON-encoded so a\n * variant key containing `,` cannot read as two variants — followed by\n * `unionRulesKey`, its mapping targets read under `options.modelName` when\n * the caller gives one. Every model fingerprint (envelope companions,\n * parameter-group wrappers) appends this, so two unions with the same\n * members but different dispatch rules never fingerprint alike.\n */\nexport function unionShapeKey(\n  model: Model,\n  variantKey: (ref: TypeRef) => string,\n  options: { sorted?: boolean; modelName?: (name: string) => string } = {},\n): string {\n  const variants = (model.variants ?? []).map(variantKey);\n  if (options.sorted) variants.sort();\n  const members = model.variants ? `|${model.compositionKind ?? ''}${JSON.stringify(variants)}` : '';\n  return `${members}${unionRulesKey(model, options.modelName)}`;\n}\n\n/**\n * The rules a named union dispatches by, independent of its members: the\n * composition keyword and the discriminator property and mapping (entries\n * sorted by value, so key order in the document plays no part; each entry\n * JSON-encoded, so a value or target containing `=` or `,` cannot read as\n * another mapping). `''` when the model declares neither. A mapping target\n * is a model name, and is read under `modelName` when the caller gives one\n * (`readDiscriminator`).\n */\nexport function unionRulesKey(model: Model, modelName?: (name: string) => string): string {\n  const parts: string[] = [];\n  if (model.compositionKind) parts.push(`kind:${model.compositionKind}`);\n  if (model.discriminator) {\n    const { property, mapping } = readDiscriminator(model.discriminator, modelName);\n    const entries = Object.entries(mapping).sort(([a], [b]) => a.localeCompare(b));\n    parts.push(`disc:${JSON.stringify(property)}${JSON.stringify(entries)}`);\n  }\n  return parts.length > 0 ? `|${parts.join('|')}` : '';\n}\n\n/**\n * `discriminator` with every mapping target — a model name — read under\n * `modelName`; the discriminator itself when no `modelName` is given. Every\n * shape comparison that reads a model reference under a renaming\n * (`ShapeReadOptions.modelName`) reads the mapping's targets through this,\n * since a rename (`renameModelRefs`) repoints them as it repoints the\n * variants.\n */\nexport function readDiscriminator(\n  discriminator: Discriminator,\n  modelName: ((name: string) => string) | undefined,\n): Discriminator {\n  if (!modelName) return discriminator;\n  const mapping = Object.fromEntries(\n    Object.entries(discriminator.mapping).map(([value, target]) => [value, modelName(target)]),\n  );\n  return { property: discriminator.property, mapping };\n}\n","import type { Constraints, EnumRef, Extensions, ExternalDocs, Model, ModelRef, Field, TypeRef } from '../ir/types.js';\nimport { collectModelRefs, collectModelTypeRefs, renameTypeRefModels, walkTypeRef } from '../ir/types.js';\nimport { toPascalCase, stripListItemMarkers, singularize } from '../utils/naming.js';\nimport type { SchemaObject } from './schemas.js';\nimport {\n  buildFieldFromSchema,\n  classifyInlineSchema,\n  componentPropertyLedger,\n  componentSchemaOf,\n  declaredComponentProperty,\n  nonObjectVariantContexts,\n  constraintsEntry,\n  deprecatedEntry,\n  extractConstraints,\n  isComponentModelRef,\n  markComponentModelRef,\n  arraySchemaOf,\n  declaresNull,\n  isInlineObjectSchema,\n  isNullSchema,\n  nullableUnionBranch,\n  unwrapNullableField,\n  unwrapNullableSchema,\n  withWrapperDeprecation,\n  withWrapperDocs,\n  nameInlineVariantEntries,\n  nameInlineVariants,\n  resolveSchemaName,\n  titleMappedVariantNames,\n  variantMemberSchemas,\n  foldSiblingProperties,\n  foldedVariantOrigin,\n} from './schemas.js';\nimport { externalDocsEntry, readExternalDocs } from './external-docs.js';\nimport { SCHEMA_CONSUMED_EXTENSIONS, extensionsOf, schemaExtensionsEntry } from './extensions.js';\nimport { copyInlineEnumMeta, shapeWithEnumFlags } from './enum-members.js';\nimport { readDiscriminator } from './union-shape.js';\n\n/**\n * Qualify an inline model name with the parent schema name.\n * If `parentName` is provided and the field name doesn't already start with\n * the parent, the result is `${parentName}${PascalField}` with the trailing\n * word singularized (e.g., Connection + Domains → ConnectionDomain).\n */\nexport function qualifyInlineModelName(baseName: string, parentName?: string): string {\n  if (!parentName) return baseName;\n  // Strip ListItem/ByExternalId markers from parent name so inline model names\n  // are clean, for response models as much as component ones.\n  // e.g., ConnectionListItem + Domains → Connection + Domain = ConnectionDomain\n  const cleanParent = stripListItemMarkers(parentName);\n  if (baseName.startsWith(cleanParent)) return baseName;\n  // Singularize the trailing PascalCase word of the combined name.\n  // Split baseName into leading words + trailing word, singularize trailing.\n  const trailingMatch = baseName.match(/^(.*?)([A-Z][a-z]*)$/);\n  if (trailingMatch) {\n    const [, prefix, trailingWord] = trailingMatch;\n    const singular = singularize(trailingWord);\n    return `${cleanParent}${prefix}${singular}`;\n  }\n  return `${cleanParent}${baseName}`;\n}\n\n/**\n * The inline model or enum names `schemaToTypeRef` would mint for `schema`\n * typed under `contextName` with `parentModelName`; empty when it mints none\n * (a `$ref`, a primitive, an array or map of those). Mirrors the naming\n * branches of `schemaToTypeRef`: an inline object in any form it recognises\n * (`properties`, an `allOf` with object members) takes\n * `qualifyInlineModelName`; a `oneOf`/`anyOf` mints one model per inline\n * object variant, named exactly as the union references them\n * (`nameInlineVariants`: `DrawingLayer`, `DrawingLayerWithOpacity`, or\n * `CircleDrawingLayer` when every variant is titled); an inline enum, or a\n * `oneOf` of string consts that collapses into one, takes the parent-prefixed\n * enum name, which is never singularized; an array or map claims whatever its\n * items or values would.\n */\nexport function mintedInlineNames(\n  contextName: string,\n  schema: SchemaObject,\n  parentModelName: string | undefined,\n): string[] {\n  return mintedInlineNameEntries(contextName, schema, parentModelName).map((entry) => entry.name);\n}\n\n/**\n * An inline name a schema mints, and whether it is context-free: a\n * title-mapped variant's title (`nameInlineVariantEntries`) is the same\n * whatever field, array or map the union sits under, where every other\n * inline name embeds the context it is typed under.\n */\nexport interface MintedInlineName {\n  name: string;\n  contextFree: boolean;\n  /** The variant schema a union variant's name was minted for; `reservedInlineNames` compares shapes through it. */\n  schema?: SchemaObject;\n}\n\n/**\n * `mintedInlineNames`, also telling for each name whether it is context-free.\n * `reserved` are the names the schema's unions must step around\n * (`nameInlineVariantEntries`), as `schemaToTypeRef` receives them for the\n * same schema (`reservedNames`); the sibling-reservation readers leave it\n * unset and read the names in isolation, while `nonObjectVariantContexts`\n * passes a variant's own set so the names it records are the ones taken.\n */\nexport function mintedInlineNameEntries(\n  contextName: string,\n  schema: SchemaObject,\n  parentModelName: string | undefined,\n  reserved?: ReadonlySet<string>,\n): MintedInlineName[] {\n  const s = unwrapNullableSchema(schema);\n  // Dispatch on the one classification `schemaToTypeRef` uses, so the names\n  // predicted here are the names it mints.\n  const kind = classifyInlineSchema(s);\n  if (kind === 'ref') return [];\n  const base = toPascalCase(contextName);\n  const modelName = (): MintedInlineName[] => [\n    { name: qualifyInlineModelName(base, parentModelName), contextFree: false },\n  ];\n  const enumName = (): MintedInlineName[] => {\n    const cleanParent = parentModelName ? stripListItemMarkers(parentModelName) : undefined;\n    return [\n      { name: cleanParent && !base.startsWith(cleanParent) ? `${cleanParent}${base}` : base, contextFree: false },\n    ];\n  };\n  if (kind === 'allOf' && s.allOf) {\n    // The one reading `schemaToTypeRef` makes of an `allOf` (`readInlineAllOf`).\n    const reading = readInlineAllOf(s.allOf, s);\n    if (reading === 'unwrapped') return mintedInlineNameEntries(contextName, s.allOf[0]!, parentModelName, reserved);\n    return reading === 'merged' ? modelName() : [];\n  }\n  const variants = kind === 'union' ? (s.oneOf ?? s.anyOf) : undefined;\n  if (variants) {\n    const nonNull = variants.filter((v) => !isNullSchema(v));\n    if (nonNull.length >= 2 && nonNull.every((v) => typeof v.const === 'string')) return enumName();\n    const variantEntries = nameInlineVariantEntries(s, modelName()[0]!.name, reserved);\n    // Every other variant mints under the context `nonObjectVariantContexts`\n    // gives it (read here without siblings but with the object variants'\n    // names): `<context>_item` / `<context>_value` for an array or map, the\n    // context itself or `<context>_variant_<n>` for a nested union, a nullable\n    // object, an `allOf` or an inline enum — stepping around the names the\n    // entry reserves — so a sibling that would take one of those names steps\n    // around it.\n    const objectVariantNames = new Map([...variantEntries].map(([variant, entry]) => [variant, entry.name]));\n    const others = [\n      ...nonObjectVariantContexts(contextName, nonNull, undefined, parentModelName, objectVariantNames, reserved),\n    ].flatMap(([variant, entry]) =>\n      mintedInlineNameEntries(entry.context, unwrapNullableSchema(variant), parentModelName, entry.reserved),\n    );\n    return [...[...variantEntries].map(([variant, entry]) => ({ ...entry, schema: variant })), ...others];\n  }\n  if (kind === 'const') return [];\n  if (kind === 'enum') return (s.enum ?? []).filter((v) => v !== null).length >= 2 ? enumName() : [];\n  if (kind === 'array' && s.items) return mintedInlineNameEntries(contextName, s.items, parentModelName, reserved);\n  if (kind === 'object') return modelName();\n  if (kind === 'map') {\n    const value = mapValueSchema(s);\n    return value ? mintedInlineNameEntries(contextName, value, parentModelName, reserved) : [];\n  }\n  return [];\n}\n\n/**\n * The inline names the other properties of an object mint\n * (`mintedInlineNameEntries`) which a `oneOf`/`anyOf` under `fieldName` must\n * not give one of its variants (`nameInlineVariants`): beside a\n * `shape_with_side` object, the `{ side }` variant of `shape` cannot become\n * `DrawingShapeWithSide`. Every context-dependent sibling name is reserved.\n * A context-free name — a title-mapped variant's title — names one shape\n * wherever it appears, so it is shared, not reserved, when this field gives\n * the same title a variant of the identical shape (`schemaShapeKey`:\n * documentation keywords ignored, property names verbatim — the rule array\n * items already use to share a singular sibling's model); a sibling giving\n * the same title a different shape, or one this field does not use, reserves\n * it, so this union's variant falls back to its context-qualified name. Each\n * sibling's names are read in isolation, without the reservations that\n * sibling would itself apply, so the set depends on sibling names and content\n * only, two unions beside each other cannot chase each other's names, and\n * the shape test is symmetric: when `Circle` means `{ radius }` on one side\n * and `{ diameter }` on the other, both fall back (`CircleDrawingShape`,\n * `CircleDrawingMarker`) and neither keeps the bare `Circle`. Empty without a\n * sibling set, as for a request body or response that is itself a union.\n *\n * Siblings are the one case decided here. A title two unions at different\n * depths of one root give different shapes — `shape` and `marker.shape` —\n * is decided before any union is named (`markContestedTitles`): such a\n * variant never keeps its title, so by the time its union is named the\n * title is not among the context-free names on either side.\n */\nexport function reservedInlineNames(\n  fieldName: string,\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n): ReadonlySet<string> {\n  const reserved = new Set<string>();\n  if (!siblings) return reserved;\n\n  // The shape this field gives each title it would keep, in isolation.\n  const ownShapes = new Map<string, string[]>();\n  const fieldSchema = siblings.get(fieldName);\n  if (fieldSchema) {\n    for (const own of mintedInlineNameEntries(fieldName, fieldSchema, parentModelName)) {\n      if (!own.contextFree || !own.schema) continue;\n      ownShapes.set(own.name, [...(ownShapes.get(own.name) ?? []), schemaShapeKey(own.schema)]);\n    }\n  }\n\n  for (const [siblingName, siblingSchema] of siblings) {\n    if (siblingName === fieldName) continue;\n    for (const minted of mintedInlineNameEntries(siblingName, siblingSchema, parentModelName)) {\n      if (!minted.contextFree) {\n        reserved.add(minted.name);\n        continue;\n      }\n      const shapes = ownShapes.get(minted.name);\n      const siblingShape = minted.schema ? schemaShapeKey(minted.schema) : undefined;\n      const identical = shapes !== undefined && siblingShape !== undefined && shapes.every((s) => s === siblingShape);\n      if (!identical) reserved.add(minted.name);\n    }\n  }\n  return reserved;\n}\n\n/**\n * Documentation keywords that do not shape a model; ignored by\n * `schemaShapeKey` at a schema's own level. `deprecated` is not one of them:\n * a deprecated copy never shares a live model's name, and a `const` member\n * deprecated on one side only makes a different enum, so `deprecated: true`\n * is shape at every level (a `false` is dropped, like `nullable: false`).\n */\nconst DOC_KEYWORDS = new Set(['description', 'title', 'example', 'examples', 'summary', 'externalDocs']);\n/** Keywords whose value maps NAMES (not keywords) to schemas: names are kept verbatim, values recurse as schemas. */\nconst NAMED_SCHEMA_MAPS = new Set(['properties', 'patternProperties', 'dependentSchemas', '$defs', 'definitions']);\n/** Keywords whose value is a single schema. */\nconst SCHEMA_KEYWORDS = new Set([\n  'items',\n  'additionalProperties',\n  'additionalItems',\n  'contains',\n  'propertyNames',\n  'not',\n  'if',\n  'then',\n  'else',\n  'unevaluatedProperties',\n  'unevaluatedItems',\n]);\n/** Keywords whose value is an ordered list of schemas. */\nconst SCHEMA_LIST_KEYWORDS = new Set(['allOf', 'oneOf', 'anyOf', 'prefixItems']);\n/** Keywords whose list value is a set: compared order-insensitively. */\nconst UNORDERED_LIST_KEYWORDS = new Set(['required', 'type']);\n\n/**\n * A canonical rendering of a schema's shape, for deciding whether two inline\n * schemas describe the same model: every structural keyword (`type`,\n * `properties`, `required`, `items`, `additionalProperties`,\n * `patternProperties`, `allOf`/`oneOf`/`anyOf`, `enum`, `const`, `format`,\n * `nullable`, ...) recursively, with keywords sorted and the `required` and\n * `type` lists order-insensitive. Documentation keywords (`description`,\n * `title`, `example`, `examples`, `summary`, `externalDocs`, `deprecated`)\n * and vendor extensions (`x-*`) are ignored, and so is `nullable: false`,\n * which the nullable unwrap leaves behind — but only where they are a\n * schema's own keywords. Inside `properties`, `patternProperties`,\n * `dependentSchemas`, `dependentRequired` and `$defs` the keys are property\n * names, kept verbatim: a field named `description` or `title` is part of the\n * shape. Enum, const and default values are compared as plain data, in\n * order, as the IR keeps them.\n */\nexport function schemaShapeKey(schema: SchemaObject): string {\n  const isRecord = (value: unknown): value is Record<string, unknown> =>\n    typeof value === 'object' && value !== null && !Array.isArray(value);\n  // Plain data (enum members, const, default): sorted keys, nothing stripped.\n  const dataKey = (value: unknown): unknown => {\n    if (Array.isArray(value)) return value.map(dataKey);\n    if (!isRecord(value)) return value;\n    const out: Record<string, unknown> = {};\n    for (const key of Object.keys(value).sort()) out[key] = dataKey(value[key]);\n    return out;\n  };\n  const schemaKey = (value: unknown): unknown => {\n    if (!isRecord(value)) return value; // boolean schemas such as `additionalProperties: true`\n    const out: Record<string, unknown> = {};\n    for (const keyword of Object.keys(value).sort()) {\n      const v = value[keyword];\n      if (DOC_KEYWORDS.has(keyword) || keyword.startsWith('x-')) continue;\n      if (keyword === 'nullable' && v === false) continue;\n      if (keyword === 'deprecated' && v !== true) continue;\n      if (NAMED_SCHEMA_MAPS.has(keyword) && isRecord(v)) {\n        const named: Record<string, unknown> = {};\n        for (const name of Object.keys(v).sort()) named[name] = schemaKey(v[name]);\n        out[keyword] = named;\n      } else if (keyword === 'dependentRequired' && isRecord(v)) {\n        const named: Record<string, unknown> = {};\n        for (const name of Object.keys(v).sort()) {\n          const names = v[name];\n          named[name] = Array.isArray(names) ? names.map(String).sort() : dataKey(names);\n        }\n        out[keyword] = named;\n      } else if (SCHEMA_KEYWORDS.has(keyword)) {\n        out[keyword] = schemaKey(v);\n      } else if (SCHEMA_LIST_KEYWORDS.has(keyword) && Array.isArray(v)) {\n        out[keyword] = v.map(schemaKey);\n      } else if (UNORDERED_LIST_KEYWORDS.has(keyword) && Array.isArray(v)) {\n        out[keyword] = v.map(String).sort();\n      } else {\n        out[keyword] = dataKey(v);\n      }\n    }\n    return out;\n  };\n  return JSON.stringify(schemaKey(schema));\n}\n\n/** Field properties that only document a field — its extensions included; two shapes that differ in these alone are one shape. */\nconst FIELD_DOC_KEYS: ReadonlySet<string> = new Set([\n  'name',\n  'description',\n  'externalDocs',\n  'example',\n  'examples',\n  'extensions',\n]);\n/** Model properties outside its shape: the name, its documentation (description, link, extensions), and the fields (fingerprinted on their own). */\nconst MODEL_IDENTITY_KEYS: ReadonlySet<string> = new Set([\n  'name',\n  'description',\n  'externalDocs',\n  'extensions',\n  'fields',\n]);\n/** Model properties `modelStructureKey` reads with the reading options — the named-union parts, whose model references are read under `readName`. */\nconst MODEL_STRUCTURE_KEYS: ReadonlySet<string> = new Set(['variants', 'compositionKind', 'discriminator']);\n/** Model properties outside `modelPropertiesKey`: the identity, the fields and the union structure, each read on its own. */\nconst MODEL_PROPERTY_KEYS_OMITTED: ReadonlySet<string> = new Set([...MODEL_IDENTITY_KEYS, ...MODEL_STRUCTURE_KEYS]);\n/** `MODEL_PROPERTY_KEYS_OMITTED` and the model's own `deprecated`, which `modelPropertiesAdmit` reads on its own (`flagAdmits`); every other property is compared verbatim. */\nconst MODEL_ADMIT_KEYS: ReadonlySet<string> = new Set([...MODEL_PROPERTY_KEYS_OMITTED, 'deprecated']);\n\n/**\n * Shape of a model, independent of field order, name and documentation:\n * every field's name, type, requiredness, limits, default and access flags,\n * plus the model's own limits, type parameters, variants and discriminator.\n * Types are read through `shapeWithEnumFlags`, so an inline enum's per-value\n * deprecation counts as its values do. Two schemas share a model only when\n * this agrees, so a body that repeats another's fields with a different\n * `minLength` or `minProperties`, or an enum member deprecated on one side\n * only, keeps its own model and its own limits. `schemaShapeKey` is the same\n * question asked of a schema before any model is built; this is asked of the\n * models, so two built by different paths (an ordinary object and a union\n * variant) compare the same way (`warnOnVariantNameClash`, the shape\n * registry in `materializeInlineSchema`, the response merge).\n */\nexport function modelFingerprint(model: Model): string {\n  const fields = model.fields\n    .map((field) => `${field.name}:${fieldShapeKey(field)}`)\n    .sort()\n    .join('|');\n  return `${fields}#${modelShapeKey(model)}`;\n}\n\n/** A field's shape as `modelFingerprint` reads it: everything but its documentation, the type through `shapeWithEnumFlags`. */\nfunction fieldShapeKey(field: Field): string {\n  return stableStringify({ ...omitKeys(field, FIELD_DOC_KEYS), type: shapeWithEnumFlags(field.type) });\n}\n\n/**\n * `modelFingerprint` read without the model's own `deprecated`: the shape a\n * deprecated copy and a live one of one schema share. What a shape the SDK\n * sends must agree with a declared model on (`modelShares`), and what the\n * merge passes compare two inline copies of one name by when only the flag\n * tells them apart (`differOnlyByDeprecation`).\n */\nexport function shapeFingerprint(model: Model): string {\n  return modelFingerprint({ ...model, deprecated: undefined });\n}\n\n/**\n * A model's shape beside its fields: its limits, type parameters,\n * `deprecated` (unless `omit` leaves it out, as `modelAdmits` does), variants\n * (through `readShape`) and dispatch rules, the mapping's targets read under\n * `options.readName` as the variants are.\n */\nfunction modelShapeKey(model: Model, options: ShapeReadOptions = {}): string {\n  return `${modelPropertiesKey(model)}${modelStructureKey(model, options)}`;\n}\n\n/**\n * A model's union structure as one string — its composition keyword, its\n * variants (through `readShape`) and its dispatch rules, the mapping's\n * targets read under `options.readName` as the variants are. What\n * `modelAdmits` compares beside the fields and the model's properties\n * (`modelPropertiesAdmit`); the list-envelope pass compares the same parts\n * by structure on its own.\n */\nfunction modelStructureKey(model: Model, options: ShapeReadOptions = {}): string {\n  const structure: Record<string, unknown> = {};\n  if (model.compositionKind) structure.compositionKind = model.compositionKind;\n  if (model.variants) structure.variants = model.variants.map((variant) => readShape(variant, options));\n  if (model.discriminator) structure.discriminator = readDiscriminator(model.discriminator, options.readName);\n  return stableStringify(structure);\n}\n\n/**\n * A model's own properties as `modelPropertiesAdmit` reads them, as one\n * string: everything but its identity (name and documentation), its fields\n * and its union structure — `deprecated`, limits (`constraints`), type\n * parameters, whatever else the IR adds to a model. `modelFingerprint`\n * carries it beside the fields and the structure, and the list-envelope\n * pass keys a companion's shape by it (`fingerprintModel`), so the shapes\n * it counts agree with the folds it allows.\n */\nexport function modelPropertiesKey(model: Model): string {\n  return stableStringify(omitKeys(model, MODEL_PROPERTY_KEYS_OMITTED));\n}\n\n/**\n * Whether `owner` admits `candidate` in the model's own properties — what\n * `modelAdmits` reads beside the fields and the union structure: the two\n * agree on `deprecated` as `flagAdmits` reads it (a live owner admits either\n * flag, a deprecated owner only a deprecated candidate), and every other\n * property — the model's limits (`minProperties`, `dependentRequired`, …),\n * its type parameters, whatever else the IR adds to a model — is identical,\n * since the owner's definition is what every site reads after a fold.\n * `MODEL_ADMIT_KEYS` names the properties read on their own, so a property\n * added to `Model` is compared verbatim until it is listed there. The one\n * definition of a model's properties a fold must preserve: `modelAdmits`\n * applies it with the structure read by key, and the list-envelope pass\n * (`admits`) with the structure compared on its own.\n */\nexport function modelPropertiesAdmit(owner: Model, candidate: Model): boolean {\n  if (!flagAdmits(owner, candidate)) return false;\n  return stableStringify(omitKeys(owner, MODEL_ADMIT_KEYS)) === stableStringify(omitKeys(candidate, MODEL_ADMIT_KEYS));\n}\n\n/** Field properties `fieldAdmits` reads on their own — the type and the requiredness — beside the documentation it ignores; every other property is compared verbatim. */\nconst FIELD_ADMIT_KEYS: ReadonlySet<string> = new Set([...FIELD_DOC_KEYS, 'type', 'required', 'deprecated']);\n/** Field properties outside `fieldPropertiesKey`: the documentation and the type, which the list-envelope pass compares by structure on its own. */\nconst FIELD_PROPERTY_KEYS_OMITTED: ReadonlySet<string> = new Set([...FIELD_DOC_KEYS, 'type']);\n\n/**\n * How `modelAdmits`, `fieldAdmits` and `typeShapeKey` read a shape before\n * they compare it.\n */\nexport interface ShapeReadOptions {\n  /**\n   * The name every model reference, and every inline enum reference, is\n   * read under on both sides before the shapes are compared — in a field's\n   * type, a union's variants and a discriminator's mapping targets alike.\n   * Absent, a reference is read under the name it carries, so a nested\n   * inline model that was renamed keeps a parent from being admitted by one\n   * whose child was not. A pass about to rename models hands the name its\n   * renaming gives each one, so two shapes compare as that renaming leaves\n   * them: the `…Json` fold (`collapseJsonSuffixModels`) reads `<Name>Json…`\n   * as `<Name>…`, so a child it will rename counts as its namesake, while a\n   * reference it will not rename is still read as it is. An inline enum\n   * reference — one carrying its `values`, named by the extractor after the\n   * model and field it sits in — is read the same way, so `PetJsonStatus`\n   * with the members of `PetStatus` counts as `PetStatus`, and with other\n   * members does not, since the members are compared with the name. A\n   * component enum reference carries no values and is never renamed by any\n   * pass, so it is always read as it is.\n   */\n  readonly readName?: (name: string) => string;\n}\n\n/**\n * Whether `owner` admits `candidate`: every value `candidate` describes is\n * one `owner` describes too, so a reference typed as `owner` in place of\n * `candidate` loses strictness and nothing else. The two have the same field\n * names, and each field admits its namesake (`fieldAdmits`): it agrees in\n * everything `modelFingerprint` reads — type, limits, default, access flags,\n * its own `deprecated` — except that `owner` may be looser where `candidate`\n * is strict, never the other way round: a field `candidate` requires may be\n * optional on `owner`, and a field type `candidate` leaves non-null may be\n * `nullable<…>` on `owner`. Only the field type's own nullable wrapper is\n * read that way; a wrapper deeper down (an array's items) must agree. The\n * models' own properties — limits, type parameters, whatever else the IR\n * adds to a model — must be identical (`modelPropertiesAdmit`), their union\n * structure — variants and dispatch rules — must agree\n * (`modelStructureKey`), and a model reference is compared by name — the\n * name it carries, or the one `options.readName` reads it under: a nested\n * inline model keeps its name, so a parent whose child was renamed is not\n * admitted by one whose child was not. The models' own `deprecated` is read\n * apart from the shape (`flagAdmits`, through `modelPropertiesAdmit`): a\n * live `owner` admits a deprecated `candidate` — the flag stays on the\n * field, parameter or envelope field that wrote the candidate's schema, not\n * on a second model of the same shape — and a deprecated `owner` admits only\n * a deprecated one, so no live reference comes to resolve to a deprecated\n * model by folding. An identical shape is admitted.\n *\n * The one rule by which an inline model folds onto a model the document\n * declares — a component schema, or a model a component's field minted — in\n * the merge passes (`settleSharedNames`) and in the shape registry of\n * `materializeInlineSchema` (`ownerShares`), both through `modelShares`, and\n * by which the `…Json` fold (`collapseJsonSuffixModels`) collapses a\n * `<Name>Json…` child onto the `<Name>…` model that already holds its folded\n * name, every reference read under the fold; two inline models share a name\n * on an identical fingerprint only. A shape the SDK sends — a request body,\n * a parameter — is the callers' exception (`modelShares`): it shares a\n * component on an identical shape only, since typed as a looser component a\n * caller could leave out what the operation requires. The list-envelope pass\n * compares its companions by a structural rule of its own, since a\n * companion's nested models are named per operation; it reads the flag by\n * `flagAdmits` as well.\n */\nexport function modelAdmits(owner: Model, candidate: Model, options: ShapeReadOptions = {}): boolean {\n  if (!modelPropertiesAdmit(owner, candidate)) return false;\n  if (owner.fields.length !== candidate.fields.length) return false;\n  const ownerFields = new Map(owner.fields.map((field) => [field.name, field]));\n  for (const field of candidate.fields) {\n    const own = ownerFields.get(field.name);\n    if (!own || !fieldAdmits(own, field, options)) return false;\n  }\n  return modelStructureKey(owner, options) === modelStructureKey(candidate, options);\n}\n\n/**\n * Whether `owner`'s own `deprecated` admits `candidate`'s: a live `owner`\n * admits a candidate of either flag, and a deprecated `owner` only a\n * deprecated one. The flag is not part of the shape a fold compares: a\n * deprecated inline schema identical to a live model it is named like shares\n * that model, its flag carried by the site that wrote the schema (a\n * `Field`, a `Parameter`, an envelope field) rather than by a second model\n * of the same shape, while a live site never resolves to a deprecated model\n * through a fold. Read by `modelAdmits` and `modelShares`, and by the\n * list-envelope pass for a companion beside a component.\n */\nexport function flagAdmits(owner: Model, candidate: Model): boolean {\n  return !owner.deprecated || !!candidate.deprecated;\n}\n\n/**\n * Whether `owner`, a model the document declares — a component schema, or a\n * model a component's field minted — shares its name with `candidate`, an\n * inline model: when it admits the shape (`modelAdmits`), or, for a shape\n * the SDK sends (`sent`: a request body, a parameter), when the two are\n * identical but for the model's own `deprecated` (`shapeFingerprint`), which\n * is read as `modelAdmits` reads it (`flagAdmits`). The one question the\n * merge passes (`settleSharedNames`) and the shape registry (`ownerShares`)\n * ask of a declared model.\n */\nexport function modelShares(owner: Model, candidate: Model, sent = false): boolean {\n  if (!sent) return modelAdmits(owner, candidate);\n  return flagAdmits(owner, candidate) && shapeFingerprint(owner) === shapeFingerprint(candidate);\n}\n\n/**\n * Whether `owner` admits `candidate` as the field of its name: the rule\n * `modelAdmits` applies to each field, on its own. The two agree in\n * everything but their documentation — type (through `fieldTypeAdmits`,\n * model and inline enum references read under `options.readName`), limits, default, access\n * flags, their own `deprecated` (`fieldFlagAgrees`: in either direction,\n * since the owner's fields are what every site reads after a fold) — except\n * that `owner` may be optional where `candidate` is required, and\n * `nullable<…>` where `candidate` is not. Everything but the type is\n * `fieldPropertiesAdmit`, which the list-envelope pass reads as well. The\n * `…Json` fold asks this of every field the base and the `…Json` model both\n * declare, since the base takes the `…Json` model's fields.\n */\nexport function fieldAdmits(owner: Field, candidate: Field, options: ShapeReadOptions = {}): boolean {\n  return fieldPropertiesAdmit(owner, candidate) && fieldTypeAdmits(owner.type, candidate.type, options);\n}\n\n/**\n * Whether `owner` admits `candidate` as the field of its name in everything\n * but the type — what `fieldAdmits` reads beside `fieldTypeAdmits`: the two\n * agree on their own `deprecated` (`fieldFlagAgrees`), `owner` is no\n * stricter on requiredness (a field `candidate` requires may be optional on\n * `owner`, never the reverse), and every other property — limits, default,\n * access flags, whatever else the IR adds to a field — is identical\n * (`FIELD_ADMIT_KEYS` names the ones read on their own, so a property added\n * to `Field` is compared verbatim until it is listed there). The one\n * definition of a field's properties a fold must preserve: `fieldAdmits`\n * applies it with the type read by shape key, and the list-envelope pass\n * (`admits`) with the type compared by structure, since a companion's nested\n * models are named per operation.\n */\nexport function fieldPropertiesAdmit(owner: Field, candidate: Field): boolean {\n  if (!fieldFlagAgrees(owner, candidate)) return false;\n  if (owner.required && !candidate.required) return false;\n  return stableStringify(omitKeys(owner, FIELD_ADMIT_KEYS)) === stableStringify(omitKeys(candidate, FIELD_ADMIT_KEYS));\n}\n\n/**\n * A field's properties as `fieldPropertiesAdmit` reads them, as one string:\n * everything but its documentation and its type — requiredness, its own\n * `deprecated`, limits, default, access flags. Two fields with the same key\n * admit each other in everything but the type; the list-envelope pass keys\n * a companion's shape by it (`fingerprintModel`) beside the structural key\n * of the type, so the shapes it counts agree with the folds it allows.\n */\nexport function fieldPropertiesKey(field: Field): string {\n  return stableStringify(omitKeys(field, FIELD_PROPERTY_KEYS_OMITTED));\n}\n\n/**\n * Whether `owner` and `candidate`, fields of one name, agree on their own\n * `deprecated`, in either direction. A field's flag has no carrier but the\n * field itself: after a fold every site reads the owner's fields, so an\n * owner whose field is live would drop the notice a candidate's deprecated\n * field gave its readers, and an owner whose field is deprecated would give\n * a candidate's readers a notice its own schema never wrote. Read by\n * `fieldAdmits` for every fold `modelAdmits` decides, and by the\n * list-envelope pass's own structural comparison (`admits`), so no fold\n * changes what any site's readers see of a field's flag.\n */\nexport function fieldFlagAgrees(owner: Field, candidate: Field): boolean {\n  return !!owner.deprecated === !!candidate.deprecated;\n}\n\n/** Whether `owner` admits every value of `candidate`'s type: the same type under the field's own nullable wrapper, which `owner` may carry where `candidate` does not. */\nfunction fieldTypeAdmits(owner: TypeRef, candidate: TypeRef, options: ShapeReadOptions): boolean {\n  if (candidate.kind === 'nullable' && owner.kind !== 'nullable') return false;\n  const inner = (ref: TypeRef): TypeRef => (ref.kind === 'nullable' ? ref.inner : ref);\n  return typeShapeKey(inner(owner), options) === typeShapeKey(inner(candidate), options);\n}\n\n/**\n * A type's shape as the admit predicates read it — every inline enum with\n * its per-value deprecation (`shapeWithEnumFlags`), every model reference\n * and inline enum reference under `options.readName` — stable-stringified,\n * so two types compare by string equality. The `…Json` fold compares a\n * base union's variants with the `…Json` model's through this, both read\n * under the fold.\n */\nexport function typeShapeKey(ref: TypeRef, options: ShapeReadOptions = {}): string {\n  return stableStringify(readShape(ref, options));\n}\n\n/**\n * `shapeWithEnumFlags(ref)`, with every model reference and every inline\n * enum reference (one carrying its `values`) renamed by `options.readName`\n * on a copy — the flags are read first, since the copy has no identity in\n * the enum side table.\n */\nfunction readShape(ref: TypeRef, options: ShapeReadOptions): unknown {\n  const shape = shapeWithEnumFlags(ref);\n  const { readName } = options;\n  if (!readName) return shape;\n  const read = structuredClone(shape) as TypeRef;\n  walkTypeRef(read, {\n    model: (r) => {\n      (r as { name: string }).name = readName(r.name);\n    },\n    enum: (r) => {\n      if (r.values) r.name = readName(r.name);\n    },\n  });\n  return read;\n}\n\n/** The entries of `value` whose key is not in `keys` and whose value is set. */\nfunction omitKeys(value: object, keys: ReadonlySet<string>): Record<string, unknown> {\n  return Object.fromEntries(\n    Object.entries(value).filter(([key, entryValue]) => entryValue !== undefined && !keys.has(key)),\n  );\n}\n\n/** `JSON.stringify` with object keys sorted and unset entries dropped, so equal shapes serialize equally. */\nfunction stableStringify(value: unknown): string {\n  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n  if (value !== null && typeof value === 'object') {\n    const record = value as Record<string, unknown>;\n    const entries = Object.keys(record)\n      .filter((key) => record[key] !== undefined)\n      .sort()\n      .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`);\n    return `{${entries.join(',')}}`;\n  }\n  return JSON.stringify(value) ?? 'undefined';\n}\n\n/**\n * The title-mapped union variants that must not keep their bare title\n * because a variant of another shape takes the same title under the same\n * root (`markContestedTitles`). Replaced whole whenever a document is marked,\n * so a schema object marked for one document is never read as contested for\n * another; empty outside an extraction, where no title is contested.\n */\nlet contestedTitledVariants = new WeakSet<SchemaObject>();\n\n/**\n * Whether `variant` is a title-mapped union variant whose title another\n * shape takes under the same root (see `markContestedTitles`). The marks are\n * on the document's variants; a folded copy of one (`foldSiblingProperties`)\n * is read through its origin.\n */\nexport function isContestedTitle(variant: SchemaObject): boolean {\n  return contestedTitledVariants.has(foldedVariantOrigin(variant) ?? variant);\n}\n\n/**\n * Decide, for a whole OpenAPI document, which title-mapped union variants\n * (`titleMappedVariantNames`) must not keep their bare title: a kept title\n * is context-free — it names one shape wherever it appears, as a component\n * name would — so when two variants anywhere under one root give the same\n * title different shapes (`schemaShapeKey`), neither can keep it, and both\n * take their context-qualified names instead (`nameInlineVariantEntries`).\n * Identical shapes under one title share one model, as between siblings\n * (`reservedInlineNames`), and a title used once is kept. Within one union\n * only the first variant to carry a title is read: a later one with the\n * same title never keeps it, whatever the document holds (`emitted` in\n * `nameInlineVariantEntries`), so it is no claim on the title. The same\n * holds across everything one union reaches without entering an object —\n * its nested unions, its array variants' items, its map variants' values,\n * a lone `allOf` member — the names `mintedInlineNameEntries` reads for the\n * union, which `nonObjectVariantContexts` decides in variant order: an\n * earlier variant's kept title is reserved for a later variant of another\n * shape and shared for the identical one. So one claim set spans that\n * group, and only its first variant per title is read here.\n *\n * A root is a schema whose inline models are collected together: every\n * `components.schemas` entry is read as one root, because one pass collects\n * their inline field models into one list and a named union's variants are\n * already compared across every component; every other schema of the\n * document — the `schema` of a request body's or response's media type, of\n * a parameter, of a response header, of a webhook payload, under `paths`,\n * `webhooks` or `components` alike — is a root of its own. The same title\n * given two shapes by two roots is not contested here: the passes that merge\n * the roots' models decide it (the first owner keeps the name, and a later\n * shape is renamed or dropped with a warning).\n *\n * Within a root, the walk follows the schema keywords only — `properties`\n * and the other name-to-schema maps, `items`, `additionalProperties`,\n * `allOf`/`oneOf`/`anyOf` and the rest of `schemaShapeKey`'s structural\n * keywords — so a property named `schema` or `title` is a property, and a\n * `$ref` is a reference to a component read under the components root, not\n * descended into. The roots are found by following the OpenAPI object model\n * (`schemaRootsOf`), the way the operation, response and webhook readers\n * do, so a name is never mistaken for a specification extension: a header\n * named `x-meta`, a component named `x-thing`, a media type `x-custom/json`\n * or a property `x-id` is read like any other, and an `x-` key is stepped\n * over only where the readers step over it or read nothing: the Paths\n * Object's and the `webhooks` map's (extensions by the specification, which\n * `extractOperations` and `extractWebhooks` step over), a Responses\n * Object's (`readFallbackResponse`) and a Callback Object's (extensions by\n * the specification; the parser reads no callbacks). Decided from the document's content\n * alone, so declaration order and depth play no part, and once per\n * document, before any union is named (`extractSchemas`), so the union\n * TypeRef and every extractor read the same decision. `undefined` clears\n * the previous document's marks.\n *\n * Each root is read with visited sets of its own, so a schema object two\n * roots share — one a `transformSpec` assigned in both places, a bundled\n * external schema inlined twice as one object — is read under each root and\n * compared with each root's other variants, and a mark from either root\n * stands: the shared variant's title is then qualified wherever it appears.\n * Within a root the same holds per claim group: a union object reached\n * under two groups — nested in `shape`, where an earlier union of the group\n * already claimed its title, and again as `wrapper.marker`, where it keeps\n * the title — is read under each, so the two shapes of the title are\n * compared and contested (`markContestedTitlesUnderRoot`). A schema that\n * refers back to itself is stopped by the ancestors on the path to it. The\n * descent over the document keeps a separate guard that never holds a\n * schema. The guards end the walk on a document that refers back to itself.\n */\nexport function markContestedTitles(document: unknown): void {\n  contestedTitledVariants = new WeakSet();\n  if (!isRecord(document)) return;\n  const components = isRecord(document['components']) ? document['components'] : undefined;\n  const schemas = components?.['schemas'];\n  if (isRecord(schemas)) markContestedTitlesUnderRoot(Object.values(schemas).filter(isSchemaRecord));\n  for (const root of schemaRootsOf(document, components)) markContestedTitlesUnderRoot([root]);\n}\n\n/** A plain object: the only value that can be a schema or a container of them. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `isRecord`, typed as a schema for the walks below. */\nfunction isSchemaRecord(value: unknown): value is SchemaObject {\n  return isRecord(value);\n}\n\n/** The Path Item Object's operation fields, the keys the operation readers dispatch on. */\nconst PATH_ITEM_OPERATIONS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const;\n\n/**\n * Every schema root of the document outside `components.schemas`, found by\n * walking the OpenAPI 3.0/3.1 object model (see `markContestedTitles`):\n *\n *   - the OpenAPI Object's `paths` and `webhooks` (a path or a name per\n *     key, an `x-` extension stepped over) to Path Item Objects; the\n *     Components Object's `responses`,\n *     `parameters`, `requestBodies`, `headers`, `pathItems` and `callbacks`\n *     (a name per key);\n *   - a Path Item's `parameters` list and operations; an Operation's\n *     `parameters`, `requestBody`, `responses` (a status code, `default`, a\n *     range or an `x-` extension per key) and `callbacks` (a name per key,\n *     each a Callback Object: an expression or an `x-` extension per key,\n *     each a Path Item);\n *   - a Parameter's or Header's `schema` and `content`; a Request Body's and\n *     a Response's `content` (a media type per key) and a Response's\n *     `headers` (a name per key); a Media Type's `schema` and `encoding` (a\n *     property name per key, each an Encoding Object with `headers`).\n *\n * A map whose keys are names is read whole, whatever the keys look like.\n * An `x-` key is stepped over in the Paths Object and the `webhooks` map,\n * where the specification makes it an extension and `extractOperations`\n * and `extractWebhooks` step over it, in a Responses Object, as\n * `readFallbackResponse` steps over it, and in a Callback Object, where the\n * specification makes it an extension (the parser reads no callbacks, so\n * nothing named under one is ever typed). A `$ref` entry\n * anywhere carries no schema of its own: the target is a component, read\n * under its own map. A `schema` is yielded and not entered, so one shared by\n * two sites is yielded for each; every other object is entered once, which\n * ends the walk on a document that refers back to itself. `example`,\n * `examples`, `links` and extensions are never entered.\n */\nfunction schemaRootsOf(\n  document: Record<string, unknown>,\n  components: Record<string, unknown> | undefined,\n): SchemaObject[] {\n  const roots: SchemaObject[] = [];\n  const entered = new WeakSet<object>();\n  /** Enter an object once; false for a non-object or one entered before. */\n  const enter = (value: unknown): value is Record<string, unknown> => {\n    if (!isRecord(value) || entered.has(value)) return false;\n    entered.add(value);\n    return true;\n  };\n  /** Every entry of a map whose keys are names. */\n  const named = (map: unknown, visit: (entry: unknown) => void): void => {\n    if (!enter(map)) return;\n    for (const entry of Object.values(map)) visit(entry);\n  };\n  /** Every entry of a map whose keys OpenAPI defines beside `x-` extensions. */\n  const keyed = (map: unknown, visit: (entry: unknown) => void): void => {\n    if (!enter(map)) return;\n    for (const [key, entry] of Object.entries(map)) if (!key.startsWith('x-')) visit(entry);\n  };\n  const listed = (list: unknown, visit: (entry: unknown) => void): void => {\n    if (!Array.isArray(list) || entered.has(list)) return;\n    entered.add(list);\n    for (const entry of list) visit(entry);\n  };\n  const schema = (value: unknown): void => {\n    if (isSchemaRecord(value)) roots.push(value);\n  };\n  const encoding = (value: unknown): void => {\n    if (enter(value)) named(value['headers'], parameter);\n  };\n  const mediaType = (value: unknown): void => {\n    if (!enter(value)) return;\n    schema(value['schema']);\n    named(value['encoding'], encoding);\n  };\n  /** A Parameter Object or a Header Object: the same schema sites. */\n  const parameter = (value: unknown): void => {\n    if (!enter(value)) return;\n    schema(value['schema']);\n    named(value['content'], mediaType);\n  };\n  const requestBody = (value: unknown): void => {\n    if (enter(value)) named(value['content'], mediaType);\n  };\n  const response = (value: unknown): void => {\n    if (!enter(value)) return;\n    named(value['headers'], parameter);\n    named(value['content'], mediaType);\n  };\n  const pathItem = (value: unknown): void => {\n    if (!enter(value)) return;\n    listed(value['parameters'], parameter);\n    for (const method of PATH_ITEM_OPERATIONS) operation(value[method]);\n  };\n  const operation = (value: unknown): void => {\n    if (!enter(value)) return;\n    listed(value['parameters'], parameter);\n    requestBody(value['requestBody']);\n    keyed(value['responses'], response);\n    named(value['callbacks'], (callback) => keyed(callback, pathItem));\n  };\n\n  // Both maps step over `x-` extensions, as `extractOperations` and\n  // `extractWebhooks` do.\n  keyed(document['paths'], pathItem);\n  keyed(document['webhooks'], pathItem);\n  if (components) {\n    named(components['responses'], response);\n    named(components['parameters'], parameter);\n    named(components['requestBodies'], requestBody);\n    named(components['headers'], parameter);\n    named(components['pathItems'], pathItem);\n    named(components['callbacks'], (callback) => keyed(callback, pathItem));\n  }\n  return roots;\n}\n\n/**\n * Mark every title-mapped variant under `roots` (read as one root) whose\n * title another variant under the same roots gives a different shape; see\n * `markContestedTitles` for the walk. The visited sets are this root's own:\n * a schema object another root also holds is read here as well, against\n * this root's variants. Within the root a schema is read once per claim\n * group it is reached from — a union object one group already read (its\n * title skipped as claimed) is read again under a property that starts a\n * group of its own, where the same title is a claim — and a schema that\n * refers back to itself is stopped by the ancestors on the path to it, which\n * ends the walk.\n */\nfunction markContestedTitlesUnderRoot(roots: readonly SchemaObject[]): void {\n  const byTitle = new Map<string, { shapes: Set<string>; variants: SchemaObject[] }>();\n  const visitedByGroup = new WeakMap<Set<string>, WeakSet<SchemaObject>>();\n  const ancestors = new Set<SchemaObject>();\n  // `claims` is the group's claim set (see `markContestedTitles`): the titles\n  // already read for the union this schema is reached from without entering\n  // an object. Only the first variant of a group to carry a title can keep\n  // it — a later one with the same title is stepped off it by its own union\n  // (`emitted` in `nameInlineVariantEntries` within one union; the kept\n  // titles `nonObjectVariantContexts` reserves across a union's non-object\n  // variants) whatever else is in the document — so a later one competes\n  // for nothing and is not read here. A schema reached any other way starts\n  // a group of its own, under which a title the first group skipped is a\n  // claim of its own, so the schema is read again there (a union object a\n  // `transformSpec` reused under another property: its title keeps the bare\n  // name there, and contests the first group's).\n  const walk = (schema: SchemaObject, claims: Set<string> = new Set()): void => {\n    if (ancestors.has(schema)) return;\n    let visited = visitedByGroup.get(claims);\n    if (!visited) visitedByGroup.set(claims, (visited = new WeakSet()));\n    if (visited.has(schema)) return;\n    visited.add(schema);\n    if (schema.$ref) return;\n    // The shapes are the ones the variants are named and built with: with\n    // `properties` written beside the union folded into them\n    // (`foldSiblingProperties`). The marks go on the document's variants,\n    // which every later fold's copies are read through (`isContestedTitle`).\n    for (const [variant, title] of titleMappedVariantNames(foldSiblingProperties(schema))) {\n      if (claims.has(title)) continue;\n      claims.add(title);\n      const entry = byTitle.get(title) ?? { shapes: new Set<string>(), variants: [] };\n      entry.shapes.add(schemaShapeKey(variant));\n      entry.variants.push(foldedVariantOrigin(variant) ?? variant);\n      byTitle.set(title, entry);\n    }\n    // The group continues through what `mintedInlineNameEntries` reads for a\n    // union: its variants, an array's items, a map's values (whether under\n    // `additionalProperties` or `patternProperties`), and the one member of a\n    // lone `allOf`. `properties` and every other keyword begin a new group.\n    ancestors.add(schema);\n    for (const [keyword, value] of Object.entries(schema)) {\n      if (NAMED_SCHEMA_MAPS.has(keyword) && isRecord(value)) {\n        const inherited = keyword === 'patternProperties' ? claims : undefined;\n        for (const sub of Object.values(value)) if (isSchemaRecord(sub)) walk(sub, inherited);\n      } else if (SCHEMA_KEYWORDS.has(keyword) && isSchemaRecord(value)) {\n        walk(value, keyword === 'items' || keyword === 'additionalProperties' ? claims : undefined);\n      } else if (SCHEMA_LIST_KEYWORDS.has(keyword) && Array.isArray(value)) {\n        const inherited =\n          keyword === 'oneOf' || keyword === 'anyOf' || (keyword === 'allOf' && value.length === 1)\n            ? claims\n            : undefined;\n        for (const sub of value) if (isSchemaRecord(sub)) walk(sub, inherited);\n      }\n    }\n    ancestors.delete(schema);\n  };\n  for (const root of roots) walk(root);\n  for (const { shapes, variants } of byTitle.values()) {\n    if (shapes.size > 1) for (const variant of variants) contestedTitledVariants.add(variant);\n  }\n}\n\n/**\n * The context name an array field's items (`kind: 'item'`) or a map field's\n * values (`kind: 'value'`) are typed and extracted under. By default it is\n * the field itself, so the inline model is the parent plus the singularized\n * field (`layers` on `Drawing` → `DrawingLayer`).\n *\n * When a sibling property of the same object would mint that very name —\n * `layer` as an inline object, an inline enum, an inline union with object\n * variants (any of whose variant names counts), or an array or map of such\n * (`mintedInlineNames`); a primitive `email` beside `emails` claims nothing\n * — the elements step aside to\n * `<field>_item` / `<field>_value`, which qualify to `<Parent><Field>Item` /\n * `<Parent><Field>Value` (`DrawingLayersItem`, `DrawingLayersValue`),\n * matching the `<Variant>Item` convention. Should a sibling mint that name\n * too (a property `layers_item`), the fallback keeps going the way\n * `variantMemberKeys` does for variants: `<field>_array_item`, then\n * `<field>_array_item2`, `<field>_array_item3`, ... for items\n * (`DrawingLayersArrayItem`, ...) and `<field>_member_value`,\n * `<field>_member_value2`, ... for values, taking the first candidate whose\n * minted name no sibling claims.\n *\n * Identical-shape sharing: when every sibling claiming the singular name is\n * an inline object whose shape is structurally identical to the items or\n * values (`schemaShapeKey`: same properties, required, types, nested inline\n * schemas and enum values; description, title and example ignored), the\n * fields share one model under the singular name. They are the same shape,\n * so one model is the right SDK type and a duplicate would only add noise;\n * should a later spec version make the shapes diverge, the split happens\n * then, which is the moment the item type genuinely changes. This\n * deliberately departs from a literal one-model-per-field reading for the\n * identical case.\n *\n * Only context-dependent names take part: a title-mapped variant's title\n * (`MintedInlineName.contextFree`) is the same under every context, so no\n * candidate could step away from it, and such a name is shared by design —\n * two sibling arrays whose items carry the same titled variants both\n * reference `Circle` and `Square` (`nameInlineVariants`). The search always\n * terminates: it stops as soon as a candidate changes nothing about the names\n * (`firstFreeElementContext`'s no-progress rule), and\n * `MAX_ELEMENT_CONTEXT_ATTEMPTS` caps it as a backstop; both return the last\n * candidate tried, deterministically.\n *\n * Decided from sibling names and schema content alone, so document order\n * plays no part. `schemaToTypeRef` and every extractor call this with the\n * same sibling set (`collectProperties`); otherwise the reference and the\n * model disagree.\n */\nexport function elementContextName(\n  fieldName: string,\n  kind: 'item' | 'value',\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  elementSchema: SchemaObject,\n): string {\n  return elementContextDecision(fieldName, kind, siblings, parentModelName, elementSchema).context;\n}\n\n/** Why `elementContextDecision` settled on a context. */\nexport type ElementContextReason =\n  /** No sibling set: nothing to decide. */\n  | 'no-siblings'\n  /** The elements mint no context-dependent name. */\n  | 'nothing-minted'\n  /** No sibling claims any name the elements mint. */\n  | 'unclaimed'\n  /** Every claimant is an inline object of the identical shape: one model is shared. */\n  | 'shared-shape'\n  /** A later candidate mints only unclaimed names. */\n  | 'free'\n  /** The names did not change from one candidate to the next, so no candidate can avoid the claim. */\n  | 'no-progress'\n  /** `MAX_ELEMENT_CONTEXT_ATTEMPTS` candidates were tried; the last one is kept. */\n  | 'cap';\n\n/** Hard cap on the candidates `firstFreeElementContext` tries; the no-progress rule stops it long before in practice. */\nexport const MAX_ELEMENT_CONTEXT_ATTEMPTS = 256;\n\n/** `elementContextName`, with the reason it decided as it did (see `ElementContextReason`). */\nexport function elementContextDecision(\n  fieldName: string,\n  kind: 'item' | 'value',\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  elementSchema: SchemaObject,\n): { context: string; reason: ElementContextReason } {\n  if (!siblings) return { context: fieldName, reason: 'no-siblings' };\n  // The names the elements would mint under a context — the context-dependent\n  // ones only, since a context-free name is shared rather than stepped from.\n  const dependentNames = (candidate: string): string[] =>\n    mintedInlineNameEntries(candidate, elementSchema, parentModelName)\n      .filter((entry) => !entry.contextFree)\n      .map((entry) => entry.name);\n  const own = dependentNames(fieldName);\n  if (own.length === 0) return { context: fieldName, reason: 'nothing-minted' };\n\n  // Every inline name the other siblings mint, with the schemas minting it.\n  const claimed = new Map<string, SchemaObject[]>();\n  for (const [siblingName, siblingSchema] of siblings) {\n    if (siblingName === fieldName) continue;\n    for (const minted of mintedInlineNames(siblingName, siblingSchema, parentModelName)) {\n      claimed.set(minted, [...(claimed.get(minted) ?? []), siblingSchema]);\n    }\n  }\n\n  const rivals = [...new Set(own.flatMap((name) => claimed.get(name) ?? []))];\n  if (rivals.length === 0) return { context: fieldName, reason: 'unclaimed' };\n  const element = unwrapNullableSchema(elementSchema);\n  const identical = (rival: SchemaObject): boolean => {\n    const sibling = unwrapNullableSchema(rival);\n    return (\n      isInlineObjectSchema(sibling) &&\n      isInlineObjectSchema(element) &&\n      schemaShapeKey(sibling) === schemaShapeKey(element)\n    );\n  };\n  if (rivals.every(identical)) return { context: fieldName, reason: 'shared-shape' };\n\n  return firstFreeElementContext(fieldName, kind, new Set(claimed.keys()), dependentNames, own);\n}\n\n/**\n * The first fallback context under which the elements mint no claimed name:\n * `<field>_item` / `<field>_value`, then `<field>_array_item` /\n * `<field>_member_value`, then `<field>_array_item2`, `…3`, ... (the way\n * `variantMemberKeys` numbers a variant's members). `mint` gives the names\n * under a candidate and `previous` those under the context tried before the\n * first candidate. The search stops with `no-progress` as soon as a\n * candidate mints the same names as the one before it — the names do not\n * depend on the context, so no candidate can avoid the claim — and with\n * `cap` after `maxAttempts` candidates; both keep the last candidate tried.\n */\nexport function firstFreeElementContext(\n  fieldName: string,\n  kind: 'item' | 'value',\n  claimed: ReadonlySet<string>,\n  mint: (candidate: string) => string[],\n  previous: readonly string[],\n  maxAttempts: number = MAX_ELEMENT_CONTEXT_ATTEMPTS,\n): { context: string; reason: ElementContextReason } {\n  const fallback = kind === 'item' ? 'array_item' : 'member_value';\n  let last = previous;\n  let candidate = fieldName;\n  for (let i = 0; i < maxAttempts; i++) {\n    candidate =\n      i === 0 ? `${fieldName}_${kind}` : i === 1 ? `${fieldName}_${fallback}` : `${fieldName}_${fallback}${i}`;\n    const minted = mint(candidate);\n    if (minted.every((name) => !claimed.has(name))) return { context: candidate, reason: 'free' };\n    if (sameNames(minted, last)) return { context: candidate, reason: 'no-progress' };\n    last = minted;\n  }\n  return { context: candidate, reason: 'cap' };\n}\n\n/** The same names, in any order. */\nfunction sameNames(a: readonly string[], b: readonly string[]): boolean {\n  if (a.length !== b.length) return false;\n  const sortedB = [...b].sort();\n  return [...a].sort().every((name, i) => name === sortedB[i]);\n}\n\n/**\n * Every property the object described by `schema` exposes, by name: its own\n * `properties`, those of its `allOf` members (following a member's `$ref`\n * into `schemas` when given, as `extractAllOfModel` does), those of a\n * nullable `oneOf`/`anyOf` wrapper's one non-null variant, read as the\n * member it wraps (`nullableUnionBranch`, the definition the model walks\n * resolve a member by, so a nullable `$ref` member's component is followed\n * here as `mergeAllOfMembers` and `readComponentAllOfMember` follow it), and\n * those of every other inline `oneOf`/`anyOf` variant, whose fields the\n * model extractors flatten in — in the order first declared, each name with\n * the declaration `declareProperty`'s precedence picks: the first\n * always-applying one, else the first variant's. This is the sibling set\n * `elementContextName` decides from; the TypeRef builder and every extractor\n * derive it through this one function so they agree.\n */\nexport function collectProperties(\n  schema: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n): Map<string, SchemaObject> {\n  const ledger = new Map<string, PropertyDeclarations>();\n  const seen = new Set<SchemaObject>();\n  const visit = (s: SchemaObject | undefined, followRef: boolean, onBranch: boolean): void => {\n    if (!s || seen.has(s)) return;\n    seen.add(s);\n    if (s.$ref) {\n      if (followRef && schemas) visit(schemas[s.$ref.split('/').pop() ?? ''], true, onBranch);\n      return;\n    }\n    for (const [key, value] of Object.entries(s.properties ?? {})) {\n      if (value) declareProperty(ledger, key, value, null, onBranch);\n    }\n    for (const sub of s.allOf ?? []) visit(sub, true, onBranch);\n    const branch = nullableUnionBranch(s);\n    if (branch) visit(branch, followRef, onBranch);\n    else for (const variant of [...(s.oneOf ?? []), ...(s.anyOf ?? [])]) visit(variant, false, true);\n  };\n  visit(schema, false, false);\n  return new Map(\n    [...ledger.values()].map((entry) => [entry.name, entry.unconditional?.schema ?? entry.conditional[0]!]),\n  );\n}\n\n/**\n * Walk all component schemas and extract inline Model definitions for fields\n * that are objects with properties, including objects reached through array\n * items, `oneOf` variants, and map (`additionalProperties` /\n * `patternProperties`) values.\n * These correspond to the ModelRef entries created by schemaToTypeRef.\n */\nexport function extractInlineModelsFromSchemas(\n  schemas: Record<string, SchemaObject> | undefined,\n  groups?: FieldInlineModelGroup[],\n): Model[] {\n  if (!schemas) return [];\n\n  const inlineModels: Model[] = [];\n  for (const [schemaName, schema] of Object.entries(schemas)) {\n    extractComponentFieldModels(schemaName, schema, schemas, inlineModels, groups);\n  }\n  return inlineModels;\n}\n\n/**\n * The inline models the fields of one component schema (`key`) mint, into\n * `results`: for every field of its model — the declaration\n * `componentPropertyLedger` chose for it, the component's own, one\n * inherited through a `$ref` member, or a branch's when no member always\n * declares the field — everything the field's type reaches (an inline\n * object, array items, map values, a union's variants, under a nullable\n * wrapper, at any depth), through the field extractor\n * (`extractInlineModelsFromProperties`), under the component's name with the\n * sibling set its fields were typed with. The one path through which the\n * field pass (`extractInlineModelsFromSchemas`, run by `parseSpec` on every\n * component) builds a component field's nested models, so a model is built\n * exactly when a component's field references it — `Puppy.meta`, inherited\n * from `Dog` and typed `PuppyMeta` under `Puppy`, has its `PuppyMeta`, and\n * the values of an inherited map their model (workos/oagen#359 review: an\n * inherited map's values were typed but never built, since the field pass\n * walked only the inline declarations and the nested-model backstop of\n * `extractSchemas` follows a reference only into an array or a union). One\n * field at a time, in field order, so the models each field\n * produced are known (`groups`) and the merge pass can rename one by the\n * field that references it. Every call sees the same siblings, reserved\n * names and results list, so the names are exactly those one call over\n * the whole schema would mint.\n */\nexport function extractComponentFieldModels(\n  key: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  results: Model[],\n  groups?: FieldInlineModelGroup[],\n): void {\n  const parentName = resolveSchemaName(key);\n  // The same sibling set `extractModel` / `extractAllOfModel` type the\n  // component's fields from, `$ref`'d allOf members included.\n  const siblings = collectProperties(schema, schemas);\n  for (const entry of componentPropertyLedger(parentName, schema, schemas).values()) {\n    const before = results.length;\n    extractInlineModelsFromProperties(\n      { properties: { [entry.name]: declaredComponentProperty(entry) } },\n      results,\n      parentName,\n      schemas,\n      siblings,\n    );\n    groups?.push({ parentName, fieldName: entry.name, models: results.slice(before) });\n  }\n}\n\n/**\n * Where a group of inline models came from, so a copy that must give up a\n * name it shares with a differently flagged or differently shaped model can\n * be renamed and exactly its own references repointed (see\n * `settleSharedNames` in the merge passes). `qualifier` is prefixed to the\n * new name — the PascalCase operation\n * name for an operation's models, as a list-envelope companion or header\n * model is qualified, the component name for a component field's; `roots`\n * are the type references the site owns — an operation's response, its\n * request body, a component field's type; `models` are the models the site\n * produced, whose fields reference one another. Renaming one of `models`\n * repoints `roots` and the other models' fields, and nothing outside the\n * bundle, so a `$ref` to a same-named component elsewhere in the document is\n * never touched.\n */\nexport interface InlineModelBundle {\n  qualifier: string;\n  roots: TypeRef[];\n  models: Model[];\n  /**\n   * Told of every rename of one of `models`, for a site whose references are\n   * copied after it is settled — a component field's, whose inline model an\n   * operation's or webhook's `allOf` merge copies a reference to\n   * (`recordFieldModelRename`). Absent for a site nothing copies from.\n   */\n  renamed?: (from: string, to: string) => void;\n  /**\n   * Set when the site's models are what the SDK sends — an operation's\n   * request body, primary or secondary, or an inline parameter — so a\n   * component shares a name with one of them only on an identical shape\n   * (`settleSharedNames`, as `ownerShares` decides for the registry): typed\n   * as a looser component, a caller could leave out what the operation\n   * requires. Absent for a shape the SDK receives — a response body or\n   * header, a webhook's payload or parameter — and for a component field's\n   * object, whose direction the document does not say.\n   */\n  sent?: boolean;\n  /**\n   * The sites of the copies that folded onto one of `models` (`foldOnto` in\n   * the merge passes), each keyed to the model it folded onto (`owner`): the\n   * copy's references name the owner from then on, so when the owner is\n   * renamed — and only then, by the owner's identity, never by name — the\n   * references in those roots and models that carry the owner's name are\n   * repointed with the site's own (`repointSite`). A rename of another model\n   * of this site leaves them alone: a model of the carried site under that\n   * name is that site's own, decided on its own. Absent until a copy folds\n   * onto one of `models`.\n   */\n  carried?: CarriedSite[];\n}\n\n/** One copy's site, carried into the site of the model it folded onto (`InlineModelBundle.carried`). */\nexport interface CarriedSite {\n  owner: Model;\n  roots: TypeRef[];\n  models: Model[];\n}\n\n/**\n * The inline models one component field produced: `fieldName` of the\n * component resolved to `parentName`. `extractInlineModelsFromSchemas` fills\n * one per field; `fieldInlineModelBundles` turns it into an\n * `InlineModelBundle` once the field's type can be looked up.\n */\nexport interface FieldInlineModelGroup {\n  parentName: string;\n  fieldName: string;\n  models: Model[];\n}\n\n/**\n * Every `ModelRef` an `allOf` merge copied from a referenced component's own\n * property (`buildMergedModel`): `Holder.ext: allOf: [{ $ref: Base }, …]`\n * types the merged model's `meta` exactly as `Base.meta` is typed, so its\n * reference names the inline model `Base.meta` produced. Such a reference\n * belongs to that component field's site, not to the site of the model it\n * sits in: when the merge passes rename the model `Base.meta` produced, the\n * references recorded under `Base.meta` are repointed with the field's own\n * (`fieldInlineModelBundles`), and no other site's rename touches them\n * (`isInheritedModelRef`). An explicit `$ref` among the copied references is\n * a component reference and is not recorded. Reset per document by\n * `extractSchemas`.\n */\n/** Each inherited reference, keyed to the `Parent.field` it was copied from, so a copy of it (`cloneTypeRef`) can be recorded under the same field. */\nconst inheritedModelRefs = new WeakMap<ModelRef, string>();\nconst inheritedModelRefsByField = new Map<string, ModelRef[]>();\n/**\n * The renames the merge passes have applied to the inline models of each\n * component field (`settleFieldInlineModels`, before any operation or\n * webhook is read), keyed `Parent.field`, so a reference an `allOf` merge\n * copies from the field afterwards (`recordInheritedModelRefs`) — typed from\n * the schema, which still mints the original name — is created under the\n * settled name. Reset per document with the inherited references.\n */\nconst fieldModelRenames = new Map<string, Map<string, string>>();\n\n/** Record that the inline model `from` of `fieldName` of the component resolved to `parentName` is now named `to`. */\nexport function recordFieldModelRename(parentName: string, fieldName: string, from: string, to: string): void {\n  const key = `${parentName}.${fieldName}`;\n  const renames = fieldModelRenames.get(key) ?? new Map<string, string>();\n  renames.set(from, to);\n  fieldModelRenames.set(key, renames);\n}\n\n/** Whether `ref` was copied from a component's property by an `allOf` merge (see `inheritedModelRefsOf`). */\nexport function isInheritedModelRef(ref: ModelRef): boolean {\n  return inheritedModelRefs.has(ref);\n}\n\n/** The references `allOf` merges copied from `fieldName` of the component resolved to `parentName`. */\nexport function inheritedModelRefsOf(parentName: string, fieldName: string): ModelRef[] {\n  return inheritedModelRefsByField.get(`${parentName}.${fieldName}`) ?? [];\n}\n\n/**\n * The models the schema pass lifts from a component field's own inline\n * schema (`collectNestedInlineModels` in `extractSchemas`: a nested object,\n * array items or a union variant, named as the field extractor names them),\n * keyed `Parent.field` by the field each was read from. The field's site\n * claims them by that origin (`fieldInlineModelBundles`), never by name:\n * `Foo.barThing` and `FooBar.thing` both spell `FooBarThing`, only one of\n * them is lifted, and the other field's site must not touch it. Reset per\n * document with the inherited references.\n */\nconst liftedFieldModels = new Map<string, Model[]>();\n\n/** Record that the schema pass lifted `model` from `fieldName` of the component resolved to `parentName`. */\nexport function recordLiftedFieldModel(parentName: string, fieldName: string, model: Model): void {\n  const key = `${parentName}.${fieldName}`;\n  const lifted = liftedFieldModels.get(key) ?? [];\n  lifted.push(model);\n  liftedFieldModels.set(key, lifted);\n}\n\n/** The models the schema pass lifted from `fieldName` of the component resolved to `parentName`, in the order it lifted them. */\nexport function liftedFieldModelsOf(parentName: string, fieldName: string): Model[] {\n  return liftedFieldModels.get(`${parentName}.${fieldName}`) ?? [];\n}\n\n/** Forget every inherited reference, field-model rename and lifted field model recorded so far: a new document is being read. */\nexport function resetInheritedModelRefs(): void {\n  inheritedModelRefsByField.clear();\n  fieldModelRenames.clear();\n  liftedFieldModels.clear();\n}\n\nfunction recordInheritedModelRefs(type: TypeRef, parentName: string, fieldName: string): void {\n  const key = `${parentName}.${fieldName}`;\n  // A copy made after the field's models were settled names them as the\n  // schema does; it is moved to the settled names first, every reference\n  // minted for an inline model and never an explicit `$ref`.\n  const renames = fieldModelRenames.get(key);\n  if (renames) renameTypeRefModels(type, renames, (ref) => !isComponentModelRef(ref));\n  walkTypeRef(type, {\n    model: (ref) => {\n      if (!isComponentModelRef(ref)) recordInheritedRef(ref, key);\n    },\n  });\n}\n\nfunction recordInheritedRef(ref: ModelRef, key: string): void {\n  inheritedModelRefs.set(ref, key);\n  const refs = inheritedModelRefsByField.get(key) ?? [];\n  refs.push(ref);\n  inheritedModelRefsByField.set(key, refs);\n}\n\n/**\n * The one way to copy a built type reference. Every pass keys a reference's\n * provenance by its identity — a `$ref` to a component\n * (`isComponentModelRef`), a reference an `allOf` merge copied from a\n * component's field (`isInheritedModelRef`), an inline enum's members and\n * link (`inlineEnumRef`) — so a structural copy (`structuredClone`, a\n * spread) silently turns a component reference into one a merge pass may\n * repoint, drops an inherited reference from its field's site, and leaves an\n * inline enum a bare name to the lift. A copy made here carries every mark\n * its original has: the component mark, the inherited record under the same\n * field, the enum's members and link; a union's mapping is copied with its\n * variants. For a type copied to a second owner — a webhook sharing a path\n * item's minting (`extractWebhooks`). A copy made only to be serialized for\n * comparison, after its flags are spelled out (`foldedVariantKey`), needs\n * none of this.\n */\nexport function cloneTypeRef(ref: TypeRef): TypeRef {\n  switch (ref.kind) {\n    case 'model': {\n      const copy: ModelRef = { ...ref };\n      if (isComponentModelRef(ref)) markComponentModelRef(copy);\n      const key = inheritedModelRefs.get(ref);\n      if (key !== undefined) recordInheritedRef(copy, key);\n      return copy;\n    }\n    case 'enum': {\n      const copy: EnumRef = { ...ref, ...(ref.values ? { values: [...ref.values] } : {}) };\n      copyInlineEnumMeta(ref, copy);\n      return copy;\n    }\n    case 'array':\n      return { ...ref, items: cloneTypeRef(ref.items) };\n    case 'nullable':\n      return { ...ref, inner: cloneTypeRef(ref.inner) };\n    case 'map':\n      return {\n        ...ref,\n        valueType: cloneTypeRef(ref.valueType),\n        ...(ref.keyType ? { keyType: cloneTypeRef(ref.keyType) } : {}),\n      };\n    case 'union':\n      return {\n        ...ref,\n        variants: ref.variants.map(cloneTypeRef),\n        ...(ref.discriminator\n          ? { discriminator: { ...ref.discriminator, mapping: { ...ref.discriminator.mapping } } }\n          : {}),\n      };\n    case 'literal':\n    case 'primitive':\n      return { ...ref };\n    default:\n      return assertNeverRef(ref);\n  }\n}\n\nfunction assertNeverRef(ref: never): never {\n  throw new Error(`Unhandled type reference: ${JSON.stringify(ref)}`);\n}\n\n/**\n * Walk a schema's properties and materialise every inline object as a model.\n * `componentSchemas` is optional and only feeds `buildFieldFromSchema`, so a\n * field that `$ref`s a component can take its `example`/`examples` from it;\n * callers without the component map at hand simply omit it.\n * `siblingProperties` is the parent object's full property set, for callers\n * that see more of it than this schema shows (see `elementContextName`).\n * `reservedNames` is set only on the re-entry for a field's array items or\n * map values: the inline names that field's siblings mint, which a union\n * among the items or values must step around exactly as `schemaToTypeRef`\n * does when it hands the same set down (`reservedNamesFor`).\n *\n * The recursion follows the document's own inline structure only: a `$ref`\n * is resolved solely to read a component's property list for typing (an\n * augmentation's inherited fields, a sibling set), never descended into, so\n * the depth is bounded by the document's inline nesting and no component\n * graph — self-extending, mutually extending, or reused at several levels —\n * can make it run away.\n */\nexport function extractInlineModelsFromProperties(\n  schema: SchemaObject,\n  results: Model[],\n  parentName?: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n  reservedNames?: ReadonlySet<string>,\n): void {\n  const properties = schema.properties ?? {};\n  const allOfSchemas = schema.allOf ?? [];\n  // Every property the parent object exposes, so array items and map values\n  // can step aside from a sibling that would mint their name (see\n  // `elementContextName`). A caller that sees more siblings than this schema\n  // shows — an `allOf` member, an envelope field — passes them in.\n  const siblings = siblingProperties ?? collectProperties(schema);\n  // The names a union under `fieldName` must not take: the set handed down\n  // for array items / map values, else what the field's siblings mint.\n  const reservedFor = (fieldName: string): ReadonlySet<string> =>\n    reservedNames ?? reservedInlineNames(fieldName, siblings, parentName);\n\n  for (const sub of allOfSchemas) {\n    if (sub.properties) {\n      extractInlineModelsFromProperties(sub, results, parentName, componentSchemas, siblings, reservedNames);\n    }\n  }\n\n  for (const [fieldName, rawFieldSchema] of Object.entries(properties)) {\n    if (!rawFieldSchema) continue;\n    // Dispatch on the shape `schemaToTypeRef` named: it strips nullable\n    // wrappers before deciding whether a field is an object, array, or map,\n    // so a nullable field must be unwrapped here the same way or its inline\n    // object / array items / map values are referenced but never extracted.\n    const fieldSchema = unwrapNullableField(rawFieldSchema);\n    // One keyword types the field (`classifyInlineSchema`, the order\n    // `schemaToTypeRef` follows), so exactly one branch below runs and the\n    // models it builds are the ones the field's type references: a schema\n    // carrying both `items` and `oneOf` yields the union's variants, never an\n    // item model under a variant's name.\n    const kind = classifyInlineSchema(fieldSchema);\n    // Direct inline object with properties (with or without explicit type: 'object',\n    // including the nullable `type: ['object', 'null']` form)\n    if (kind === 'object') {\n      const baseName = toPascalCase(fieldName);\n      const modelName = qualifyInlineModelName(baseName, parentName);\n      results.push(buildInlineModel(modelName, fieldSchema, componentSchemas));\n      extractInlineModelsFromProperties(fieldSchema, results, modelName, componentSchemas);\n    }\n\n    // Array: schemaToTypeRef types the items with the field's own context\n    // name and parent, so every inline model reachable through the items — a\n    // plain inline object, the variants of an `items.oneOf`, a nested array\n    // or map — is named exactly as if the items schema were the field itself\n    // (`shapes` → `CreateDrawingRequestShape`, `SquareCreateDrawingRequestShape`).\n    // Re-enter with a synthetic property named by `elementContextName` — the\n    // field itself, or `<field>_item` when a sibling would take the singular\n    // name — so the branches in this function do the extraction with\n    // byte-for-byte identical naming.\n    const arrayItems = kind === 'array' ? fieldSchema.items : undefined;\n    if (arrayItems) {\n      const itemContext = elementContextName(fieldName, 'item', siblings, parentName, arrayItems);\n      extractInlineModelsFromProperties(\n        { properties: { [itemContext]: arrayItems } },\n        results,\n        parentName,\n        componentSchemas,\n        undefined,\n        reservedFor(fieldName),\n      );\n    }\n\n    // Map (`additionalProperties` / `patternProperties` on a property-less\n    // object): schemaToTypeRef types the values the same way it types array\n    // items, so a map of inline objects references `${Parent}${SingularField}`\n    // (`layers` on `CreateDrawingRequest` → `CreateDrawingRequestLayer`), or\n    // `<Parent><Field>Value` when a sibling takes the singular name. Re-enter\n    // with the value schema as a synthetic property of that name.\n    if (kind === 'map') {\n      const valueSchema = mapValueSchema(fieldSchema);\n      if (valueSchema) {\n        const valueContext = elementContextName(fieldName, 'value', siblings, parentName, valueSchema);\n        extractInlineModelsFromProperties(\n          { properties: { [valueContext]: valueSchema } },\n          results,\n          parentName,\n          componentSchemas,\n          undefined,\n          reservedFor(fieldName),\n        );\n      }\n    }\n\n    // A field expressed via `allOf`, read as `schemaToTypeRef` reads it\n    // (`readInlineAllOf`, the one decision):\n    //  - `'merged'` — a `$ref` member plus an inline object member\n    //    (`isInlineAllOfMember`), or several inline members one of which\n    //    declares properties inline (`declaresInlineProperties`): the field\n    //    is typed as the model `<Parent><Field>`; merge the referenced\n    //    component(s) and the inline members into that model\n    //    (`materializeMergedAllOf`), with every inherited property typed\n    //    under its component — `Base.meta` stays `BaseMeta`, a\n    //    self-reference `Base.child` stays `BaseChild` — and only the inline\n    //    members' own properties, a variant's included, qualified under the\n    //    merged model and recursed into. The component pass already\n    //    materialized whatever the inherited properties reference, so nothing\n    //    is duplicated; a component that extends itself through a field\n    //    simply points back at a model that exists, and a component reused by\n    //    several nested augmentations hands each of them its full field\n    //    list. The model is built whatever fields the merge yields, since the\n    //    reference that names it exists;\n    //  - `'unwrapped'` — a single non-`$ref` member: typed as the field\n    //    itself, so re-enter with it as the field (same siblings);\n    //  - `'reference'` — `$ref` members only: a plain reference to the first\n    //    component, nothing to materialize.\n    if (kind === 'allOf' && fieldSchema.allOf) {\n      const reading = readInlineAllOf(fieldSchema.allOf, fieldSchema, componentSchemas);\n      if (reading === 'merged') {\n        const modelName = qualifyInlineModelName(toPascalCase(fieldName), parentName);\n        materializeMergedAllOf(modelName, fieldSchema, results, componentSchemas);\n      } else if (reading === 'unwrapped') {\n        // Re-enter with the member as the field (same siblings), carrying the\n        // wrapper's limits, flag and link (`unwrappedAllOfMember`).\n        extractInlineModelsFromProperties(\n          { properties: { [fieldName]: unwrappedAllOfMember(fieldSchema, fieldSchema.allOf[0]!) } },\n          results,\n          parentName,\n          componentSchemas,\n          siblings,\n          reservedNames,\n        );\n      }\n    }\n\n    // oneOf/anyOf containing objects — extract every inline object variant as a\n    // model so each gets its own typed class, under the names the union\n    // TypeRef references them by (`nameInlineVariants`, the one place that\n    // decides them): variant 0 keeps the bare qualified inline name\n    // (`ApiKeyCreatedDataOwner`), later variants take their const-\n    // discriminator value (`UserApiKeyCreatedDataOwner`), their title, a\n    // distinguishing property (`DrawingShapeWithSide`) or, for identical\n    // property sets, the position counter — never a name a sibling property\n    // mints (`reservedInlineNames`), nor a title another shape takes under\n    // the same root (`isContestedTitle`), so no variant overwrites another\n    // field's model.\n    const unionVariants = kind === 'union' ? (fieldSchema.oneOf ?? fieldSchema.anyOf) : undefined;\n    if (unionVariants) {\n      const inlineObjectVariants = unionVariants.filter((v) => isInlineObjectSchema(v));\n      // Decided once, for the object variants' models and for the collection\n      // contexts, which step around those models' children.\n      const variantNames: ReadonlyMap<SchemaObject, string> =\n        inlineObjectVariants.length > 0\n          ? nameInlineVariants(\n              fieldSchema,\n              qualifyInlineModelName(toPascalCase(fieldName), parentName),\n              reservedFor(fieldName),\n            )\n          : new Map();\n      if (inlineObjectVariants.length > 0) {\n        const existingByName = new Map(results.map((r) => [r.name, r]));\n        for (const variant of inlineObjectVariants) {\n          const variantName = variantNames.get(variant);\n          if (variantName === undefined) continue;\n          const existing = existingByName.get(variantName);\n          if (existing) {\n            // The name is already in `results`: a context-free title shared\n            // by a variant of the identical shape — the one case the naming\n            // rules let two variants take one name — references the model\n            // already built. Anything else is a clash the naming rules did\n            // not reach (a title coinciding with another field's model, two\n            // roots read into one list), and the union's reference will\n            // resolve to the model that keeps the name, so say so rather\n            // than drop the variant silently.\n            warnOnVariantNameClash(existing, variant, variantName, parentName, componentSchemas, results);\n            continue;\n          }\n          const model = buildInlineModel(variantName, variant, componentSchemas);\n          existingByName.set(variantName, model);\n          results.push(model);\n          extractInlineModelsFromProperties(variant, results, variantName, componentSchemas);\n          // A multi-type variant (`type: ['object', 'array']`) types the\n          // items of its array member under the variant's name\n          // (`<Variant>Item`, see `variantMemberSchemas`); re-enter with\n          // them as a same-named synthetic property so the models line up.\n          extractInlineModelsFromProperties(\n            { properties: variantMemberSchemas(variant, variantName) },\n            results,\n            variantName,\n            componentSchemas,\n          );\n        }\n      }\n      // Every other variant that mints a name is typed under the context\n      // `nonObjectVariantContexts` gives it — `<field>_item` / `<field>_value`\n      // for an array or map; the field itself or `<field>_variant_<n>` for a\n      // nested union, a nullable wrapper around an object, an `allOf`, an\n      // inline enum — apart from the object variants' and each other's names,\n      // so whatever it mints is extracted the same way: re-entered as a\n      // property of that name, the branches above materialize it exactly as\n      // the reference names it (`ReqShapesItem` for a `shapes` variant's\n      // items; `ReqShapeVariant2`, `BReqShapeVariant2` for the inline object\n      // variants of a union nested under the second variant). The context\n      // already stepped around the siblings; the re-entry sees none, exactly\n      // as `schemaToTypeRef` types the variant.\n      for (const [variant, { context, reserved }] of nonObjectVariantContexts(\n        fieldName,\n        unionVariants,\n        siblings,\n        parentName,\n        variantNames,\n        reservedNames,\n      )) {\n        const member = unwrapNullableField(variant);\n        extractInlineModelsFromProperties(\n          { properties: { [context]: member } },\n          results,\n          parentName,\n          componentSchemas,\n          undefined,\n          reserved,\n        );\n      }\n    }\n  }\n}\n\n/**\n * Warn when a union variant named `variantName` finds a model of that name\n * already in the results list and the two are not the same shape: the\n * variant is not extracted, and the union's reference resolves to the model\n * that keeps the name. The comparison is between the models themselves —\n * the one in the list, however it was built (an ordinary object, an `allOf`\n * merge, a variant), and the one the variant would have produced, with the\n * nested models each would build — by `deepModelFingerprint`, so a `detail`\n * that is `{ radius }` under the first and `{ diameter }` under the variant\n * counts as a different shape although both parents reference one\n * `DrawingCircleDetail`, and an ordinary object of exactly the variant's\n * shape, nested models included, shares the name silently, as a sibling\n * variant of the identical shape does. The warning names the nested models\n * that differ when the parents' own fields agree. Once per variant, since\n * each is visited once.\n */\nfunction warnOnVariantNameClash(\n  existing: Model,\n  variant: SchemaObject,\n  variantName: string,\n  parentName: string | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  results: readonly Model[],\n): void {\n  const candidate = buildInlineModel(variantName, variant, componentSchemas);\n  const built: Model[] = [candidate];\n  extractInlineModelsFromProperties(variant, built, variantName, componentSchemas);\n  if (deepModelFingerprint(existing, results) === deepModelFingerprint(candidate, built)) return;\n  const fieldList = (model: Model): string => model.fields.map((f) => f.name).join(', ') || '(no fields)';\n  const site = parentName ? ` under ${parentName}` : '';\n  const differing =\n    modelFingerprint(existing) === modelFingerprint(candidate)\n      ? `; nested models differ: ${differingNestedModels(existing, results, candidate, built).join(', ')}`\n      : '';\n  console.warn(\n    `[oagen] Warning: Inline model \"${variantName}\" is minted twice with different shapes${site} ` +\n      `(fields: ${fieldList(existing)} | ${fieldList(candidate)}${differing}) ` +\n      `— keeping the first; the second union's reference resolves to it`,\n  );\n}\n\n/**\n * `modelFingerprint` of `model` extended with the deep fingerprint of every\n * inline model its fields and variants reference, read from `models`, the\n * list it was built into — so two models of the same fields whose nested\n * models differ compare as different shapes. A referenced name no model in\n * the list defines is a component's and stays a name, the same on both\n * sides; a model that reaches itself is read once per path. Sorted by name,\n * so field order plays no part here either.\n */\nexport function deepModelFingerprint(model: Model, models: readonly Model[]): string {\n  const byName = new Map(models.map((m) => [m.name, m]));\n  const visiting = new Set<string>();\n  const deep = (m: Model): string => {\n    visiting.add(m.name);\n    const nested = [...new Set(collectModelTypeRefs(m).flatMap((ref) => collectModelRefs(ref)))].sort().map((name) => {\n      const referenced = byName.get(name);\n      return referenced && !visiting.has(name) ? `${name}=${deep(referenced)}` : name;\n    });\n    visiting.delete(m.name);\n    return `${modelFingerprint(m)}@{${nested.join(',')}}`;\n  };\n  return deep(model);\n}\n\n/** The names of the inline models `a` and `b` reference, directly or below, whose deep fingerprints differ or that only one side defines; sorted. */\nfunction differingNestedModels(a: Model, aModels: readonly Model[], b: Model, bModels: readonly Model[]): string[] {\n  const reachable = (model: Model, models: readonly Model[]): Map<string, string> => {\n    const byName = new Map(models.map((m) => [m.name, m]));\n    const found = new Map<string, string>();\n    const visit = (m: Model): void => {\n      for (const name of collectModelTypeRefs(m).flatMap((ref) => collectModelRefs(ref))) {\n        const referenced = byName.get(name);\n        if (!referenced || found.has(name)) continue;\n        found.set(name, deepModelFingerprint(referenced, models));\n        visit(referenced);\n      }\n    };\n    visit(model);\n    return found;\n  };\n  const left = reachable(a, aModels);\n  const right = reachable(b, bModels);\n  const names = new Set([...left.keys(), ...right.keys()]);\n  return [...names].filter((name) => left.get(name) !== right.get(name)).sort();\n}\n\n/** One property of a merged inline `allOf` and the component it is inherited from (null: an inline member's own). */\nexport interface MergedProperty {\n  name: string;\n  schema: SchemaObject;\n  origin: { name: string; schema: SchemaObject } | null;\n}\n\n/** An inline `allOf` read as one object shape; see `mergeAllOfMembers`. */\nexport interface MergedAllOf {\n  /** Every property the members declare, each name once, in the order first declared. */\n  properties: MergedProperty[];\n  /** The wrapper's `required` and every always-applying member's, in order; a variant's is not read. */\n  required: string[];\n  /** The `$ref` members a component schema answered, each once, in order (a member's component chain included). */\n  resolvedRefs: string[];\n  /** The `$ref` members no component schema answers, each once, in order; they contribute nothing. */\n  unresolvedRefs: string[];\n  description: string | undefined;\n  /** The wrapper's own link, read like its description. */\n  externalDocs: ExternalDocs | undefined;\n  /** The wrapper's own limits conjoined with its inline members' (a `$ref` member contributes only its sibling keywords). */\n  constraints: Constraints | undefined;\n  /** `true` when the wrapper itself says `deprecated: true`; a member's flag is not read (a `$ref` member's stays on its model). */\n  deprecated: boolean | undefined;\n  /** The wrapper's own extensions (`extensionsOf`), read like its link; a member's stay on that member, a `$ref` member's on its component. */\n  extensions: Extensions | undefined;\n}\n\n/**\n * Whether a schema declares object properties inline: `properties` of its\n * own, or — through a nested `allOf` member or a `oneOf`/`anyOf` variant —\n * a schema that does. A `$ref` declares none here, whatever its component\n * holds: it is a reference, and the component keeps its own fields.\n *\n * This is the question every site that reads an inline `allOf` asks of a\n * member — `allOfTypesSchema` (through `classifyInlineSchema`),\n * `schemaToTypeRef`, `mintedInlineNameEntries` and\n * `extractInlineModelsFromProperties` — so they agree on whether the `allOf`\n * mints a merged model: a member written as `{ oneOf: [{ properties: … },\n * …] }` carries fields `mergeAllOfMembers` reads, so it counts exactly as a\n * member written as `{ properties: … }` does (workos/oagen#283: it did not,\n * and `allOf: [{ $ref }, { oneOf: […] }]` was typed as the bare reference\n * while the variants' fields were dropped).\n */\nexport function declaresInlineProperties(schema: SchemaObject): boolean {\n  const seen = new Set<SchemaObject>();\n  const declares = (s: SchemaObject): boolean => {\n    if (seen.has(s)) return false;\n    seen.add(s);\n    if (s.$ref) return false;\n    if (s.properties) return true;\n    return (s.allOf ?? []).some(declares) || (s.oneOf ?? s.anyOf ?? []).some(declares);\n  };\n  return declares(schema);\n}\n\n/**\n * Whether an `allOf` member is an inline object member — one that, beside a\n * `$ref` member, makes the `allOf` an augmentation model rather than a plain\n * reference (`schemaToTypeRef`): not a `$ref`, and either `type: 'object'`\n * or declaring properties inline (`declaresInlineProperties`).\n */\nexport function isInlineAllOfMember(member: SchemaObject): boolean {\n  return !member.$ref && (member.type === 'object' || declaresInlineProperties(member));\n}\n\n/** How an inline `allOf` is read; see `readInlineAllOf`. */\nexport type InlineAllOfReading = 'merged' | 'unwrapped' | 'reference';\n\n/**\n * The one decision every site makes of an inline `allOf` — `schemaToTypeRef`\n * when it types the schema, `mintedInlineNameEntries` when it predicts the\n * names, the field extractor and `extractInlineModelDeep` when they build\n * the models, `extractDirectResource` when it reads a primary response body\n * — so a model is built exactly when a reference names it:\n *\n *   - `'merged'`: a `$ref` member beside an inline object member\n *     (`isInlineAllOfMember`), or, without a `$ref`, several members one of\n *     which declares properties inline (`declaresInlineProperties`). The\n *     schema is the merged model `mergeAllOfMembers` reads, built with\n *     whatever fields the merge yields: an empty `properties: {}` is an\n *     inline object with no fields, as it is as a plain field or a union\n *     variant (`isInlineObjectSchema`), so its model is built with none\n *     rather than left for the reference to dangle on.\n *   - `'unwrapped'`: a single non-`$ref` member with nothing beside it that\n *     adds to it, typed and extracted as the schema itself\n *     (`unwrappedAllOfMember`, which carries the wrapper's limits, flag and\n *     link onto it). A `required` list the wrapper writes beside a lone\n *     member that declares properties (`declaresInlineProperties`) adds to\n *     it: the schema is then the merged model, which reads both lists\n *     (workos/oagen#359 review: the unwrap carried the member's `required`\n *     only, so `{ allOf: [{ properties: { name } }], required: [name] }`\n *     left `name` optional). Beside a member that declares none — an\n *     array, a primitive, an enum — `required` constrains nothing, and the\n *     member is the schema.\n *   - `'reference'`: a single `$ref` member with nothing beside it that adds\n *     to the component — a `description`, limits — is that component, and\n *     nothing is minted. A second `$ref` member, or a `required` list\n *     (`wrapper`'s own, or a member's) adds to it: the schema is then the\n *     merged model, which carries every component's properties and every\n *     `required` (workos/oagen#359 review: `allOf: [{ $ref: Pet },\n *     { $ref: Owner }]` was `Pet`, `Owner`'s fields gone; `allOf: [{ $ref:\n *     Pet }], required: [name]` was `Pet` with `name` optional). A\n *     `required` adds to the component only when the component declares\n *     properties the merge would read — its own, or its `allOf` chain's\n *     (`refContributesProperties`): JSON Schema applies `required` to an\n *     object instance only, so beside a `$ref` to an array, a primitive, an\n *     enum or a union component it constrains nothing, and the reference\n *     stands (the same review: `{ allOf: [{ $ref: Pets }], required: [name] }`\n *     with `Pets` an array became an empty object model). A ref no\n *     component answers declares nothing here, and stays the reference.\n *\n * `allOfTypesSchema` admits no other shape as an `allOf`. `wrapper` is the\n * schema the `allOf` is written on, for its own `required`; a site reading\n * bare members passes none. `componentSchemas` resolves the `$ref`; a site\n * handed none reads the document's components (`componentSchemaOf`), so\n * every site decides alike.\n */\nexport function readInlineAllOf(\n  members: readonly SchemaObject[],\n  wrapper?: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): InlineAllOfReading {\n  const refs = members.filter((m) => m.$ref !== undefined);\n  if (refs.length > 0) {\n    if (members.some(isInlineAllOfMember) || refs.length > 1) return 'merged';\n    const addsRequired =\n      [wrapper, ...members].some((s) => s !== undefined && (s.required?.length ?? 0) > 0) &&\n      refContributesProperties(refs[0]!.$ref!, componentSchemas);\n    return addsRequired ? 'merged' : 'reference';\n  }\n  if (members.length === 1) {\n    const only = members[0]!;\n    const addsRequired = (wrapper?.required?.length ?? 0) > 0 && declaresInlineProperties(only);\n    return addsRequired ? 'merged' : 'unwrapped';\n  }\n  return members.some(declaresInlineProperties) ? 'merged' : 'reference';\n}\n\n/**\n * Whether the component `ref` names contributes properties to an `allOf`\n * merge — declares `properties` of its own, or through its `allOf` chain\n * (a member's `$ref` followed the same way), the reading `mergeAllOfMembers`\n * makes of a `$ref` member; a union the component carries is not read\n * there, so it does not count. False for an array, a primitive, an enum, a\n * union-only component, and for a ref no component answers. A chain that\n * returns to a schema it has read declares nothing more.\n */\nfunction refContributesProperties(ref: string, componentSchemas?: Record<string, SchemaObject>): boolean {\n  const seen = new Set<SchemaObject>();\n  const declares = (schema: SchemaObject | undefined): boolean => {\n    if (!schema || seen.has(schema)) return false;\n    seen.add(schema);\n    if (schema.$ref) return declares(componentSchemaOf(schema.$ref, componentSchemas));\n    if (Object.keys(schema.properties ?? {}).length > 0) return true;\n    return (schema.allOf ?? []).some(declares);\n  };\n  return declares(componentSchemaOf(ref, componentSchemas));\n}\n\n/**\n * The lone member of an `allOf`, read as the schema itself. The wrapper's own\n * keywords, conjoined with the member's, are the schema's limits (see\n * `extractConstraints`), so they ride along with the member and the model\n * built from it carries the same constraints; its `deprecated` is the\n * wrapper's alone, as `Field.deprecated` reads it, and its documentation —\n * text, link, examples, extensions — is the wrapper's wherever the wrapper\n * has any, by the one wrapper rule `schemaToTypeRef` applies to the member\n * it types (`withWrapperDocs`), so the model built from the member and an\n * inline enum lifted from it are documented by the wrapper alike. Nested\n * under a nullable wrapper, the outer wrapper's documentation has already\n * landed on this one (`unwrapNullableField`), so the layers compose\n * outermost-first.\n */\nexport function unwrappedAllOfMember(wrapper: SchemaObject, member: SchemaObject): SchemaObject {\n  // The wrapper's documentation layer — text, link, examples, extensions —\n  // rides onto the member by the one wrapper rule (`withWrapperDocs`), the\n  // wrapper's winning, as the type builder gives the same wrapper on a field.\n  return withWrapperDocs(withWrapperDeprecation({ ...member, ...extractConstraints(wrapper) }, wrapper), wrapper);\n}\n\n/**\n * The declarations one property name received from the members of an\n * `allOf`, in the order first declared; see `declareProperty`.\n */\nexport interface PropertyDeclarations {\n  name: string;\n  /** The always-applying declaration that types the property (`combineDeclarations`), with the component it is inherited from (`null` for the schema's own). */\n  unconditional?: { schema: SchemaObject; origin: MergedProperty['origin'] };\n  /** Each branch-only declaration — a `oneOf`/`anyOf` variant's — in order. */\n  conditional: SchemaObject[];\n}\n\n/**\n * Whether a declaration says what an instance is: a `type`, a `$ref`,\n * `properties`, `items`, an `enum` or `const`, a composition, or an\n * `additionalProperties`/`patternProperties` map. One that declares none —\n * a bare `description`, `title`, `example`, `deprecated`, `default`, or a\n * validation keyword on its own (`minimum: 1`) — annotates or constrains a\n * type another declaration gives, and is never read as the type itself\n * (`combineDeclarations`).\n */\nexport function declaresType(schema: SchemaObject): boolean {\n  return (\n    schema.type !== undefined ||\n    schema.$ref !== undefined ||\n    schema.properties !== undefined ||\n    schema.items !== undefined ||\n    schema.enum !== undefined ||\n    schema.const !== undefined ||\n    schema.allOf !== undefined ||\n    schema.oneOf !== undefined ||\n    schema.anyOf !== undefined ||\n    schema.additionalProperties !== undefined ||\n    schema.patternProperties !== undefined\n  );\n}\n\n/**\n * The always-applying declaration of one property once a second arrives, in\n * document order — the one rule for a name two members declare, applied by\n * `declareProperty` for every `allOf` merge (a merged model's, a component's)\n * and by the one property walk (`collectObjectProperties`) for a list\n * envelope's companions, a wrapper's stop field and every `dataPath`\n * segment, so a model's field and a list's stop field are typed from the\n * same declaration (workos/oagen#308 merge review: the walk conjoined two\n * `result` objects while the model kept the first, so `endOfIteration`\n * named `result.total_pages` on a model whose `result` had no such field).\n *\n * The first declaration that declares a type (`declaresType`) types the\n * property, whatever comes after it; a declaration that declares none never\n * does, before or after, and only fills in the keywords the typing one\n * leaves unset — so `has_more: { type: 'boolean' }` beside an `allOf`\n * member's `has_more: { description: 'More pages' }` is a described boolean\n * whichever is read first. Two typing declarations conjoin as JSON Schema\n * applies both: two inline objects (`isInlineObjectSchema`) merge their\n * properties — a name both declare by this same rule — and unite their\n * `required`, the later's other keywords (a `description`) over the\n * earlier's; two arrays, each under a nullable wrapper of any spelling or\n * none (`arraySchemaOf`), merge as the bare arrays they wrap, so the `items`\n * land in the one array that is then read, whichever declaration wore the\n * wrapper: the later `items` when they say something and the earlier when\n * the later declaration only constrains the array (`minItems: 1`) or allows\n * any item (`items: {}`), so `data: User[]` is not downgraded in either\n * order; the later's other keywords over the earlier's; and `type:\n * ['array', 'null']` when either admits `null` (`declaresNull`), else\n * `type: 'array'`. Any other pair keeps the first as written. Returns\n * `held` itself when `next` adds nothing to it, so a lone declaration keeps\n * its identity.\n */\nexport function combineDeclarations(held: SchemaObject, next: SchemaObject): SchemaObject {\n  if (!declaresType(held) && declaresType(next)) return { ...held, ...next };\n  if (declaresType(held) && declaresType(next)) return conjoinTypedDeclarations(held, next);\n  const unset = Object.entries(next).filter(([key]) => !Object.hasOwn(held, key));\n  return unset.length === 0 ? held : { ...Object.fromEntries(unset), ...held };\n}\n\n/** Two typing declarations of one property, conjoined as `combineDeclarations` describes; `first` when they do not combine. */\nfunction conjoinTypedDeclarations(first: SchemaObject, second: SchemaObject): SchemaObject {\n  if (isInlineObjectSchema(first) && isInlineObjectSchema(second)) {\n    const properties: Record<string, SchemaObject | undefined> = { ...first.properties };\n    for (const [key, schema] of Object.entries(second.properties ?? {})) {\n      if (!schema) continue;\n      const held = properties[key];\n      properties[key] = held ? combineDeclarations(held, schema) : schema;\n    }\n    const required = [...new Set([...(first.required ?? []), ...(second.required ?? [])])];\n    return { ...first, ...second, properties, ...(required.length > 0 && { required }) };\n  }\n  const firstArray = arraySchemaOf(first);\n  const secondArray = firstArray && arraySchemaOf(second);\n  if (firstArray && secondArray) {\n    const says = (items: SchemaObject | undefined): boolean => items !== undefined && Object.keys(items).length > 0;\n    const items = says(secondArray.items) ? secondArray.items : firstArray.items;\n    const { nullable: _firstFlag, ...firstBare } = firstArray;\n    const { nullable: _secondFlag, ...secondBare } = secondArray;\n    return {\n      ...firstBare,\n      ...secondBare,\n      ...(items !== undefined && { items }),\n      type: declaresNull(first) || declaresNull(second) ? ['array', 'null'] : 'array',\n    };\n  }\n  return first;\n}\n\n/**\n * Record one declaration of `name` in `ledger`: the one precedence rule\n * every `allOf` merge applies, whether the declaration arrives from a direct\n * member, a nested `allOf` member or a `oneOf`/`anyOf` variant, at any\n * depth. Of the always-applying declarations, the first that declares a\n * type wins, whatever is declared before or after it, and a typeless one\n * only annotates it (`combineDeclarations`); the entry's origin is the\n * typing declaration's. A branch-only declaration (`onBranch`) is only a\n * fallback, kept in order for the reader to use when no member always\n * declares the name — `mergeAllOfMembers` as the union of the distinct\n * branch declarations, the component readers (`extractAllOfModel`,\n * `extractDiscriminatedAllOfVariantModels`) as the first branch's. Names are\n * matched by own name (a `Map`), so `constructor`, `toString` and\n * `__proto__` are properties like any other.\n */\nexport function declareProperty(\n  ledger: Map<string, PropertyDeclarations>,\n  name: string,\n  schema: SchemaObject,\n  origin: MergedProperty['origin'],\n  onBranch: boolean,\n): void {\n  let entry = ledger.get(name);\n  if (!entry) ledger.set(name, (entry = { name, conditional: [] }));\n  if (onBranch) entry.conditional.push(schema);\n  else if (!entry.unconditional) entry.unconditional = { schema, origin };\n  else {\n    const held = entry.unconditional;\n    const combined = combineDeclarations(held.schema, schema);\n    // The origin is the typing declaration's. A declaration conjoined from\n    // two components' (`combined` is neither as written) is no component's\n    // own — no component model builds what it nests — so it becomes the\n    // merged model's own, built under its name like a union of branches.\n    const typesIt = !declaresType(held.schema) && declaresType(schema);\n    const conjoined = combined !== held.schema && combined !== schema && held.origin?.name !== origin?.name;\n    entry.unconditional = { schema: combined, origin: conjoined ? null : typesIt ? origin : held.origin };\n  }\n}\n\n/**\n * Merge an inline `allOf` into one object shape, remembering where each\n * property comes from. Every site that types an inline `allOf` reads it\n * through this one function — a model field (of a component or of any\n * inline model), a request body, a response body of every kind (primary,\n * secondary media type, error, `default` and range), a response header, a\n * webhook payload or parameter, array items, map values, a union's `allOf`\n * variant, and a field nested under a discriminated component variant — so\n * the same schema has the same fields wherever it appears.\n *\n * Members are read in document order, the wrapper's own `properties` and\n * `required` first. A `$ref` member is resolved against `componentSchemas`\n * by its component name, as `extractAllOfModel` does, and contributes its\n * component's `properties` — its own, written beside its `allOf`, and those\n * of its `allOf` chain, in the order `extractAllOfModel` reads them\n * (`componentAllOfMembers`) — tagged with that component's model name, so the merged\n * model can type them exactly as the component's own model does; a ref no\n * component answers contributes nothing and is listed in `unresolvedRefs`.\n * The component tagged is the one whose own model carries the field under\n * its name: an `allOf` component that inherits it stays the origin of\n * everything reached inside its chain (`DogMeta`), while a bare alias\n * (`Hop: { $ref: Base }`), a nullable alias (`Alias: { oneOf: [{ $ref: Base\n * }, { type: 'null' }] }`) or a chain of either declares nothing of its own\n * and builds no model, so a reference met inside one starts its own origin\n * (`Base.meta` stays `BaseMeta`; workos/oagen#308 round 4).\n * An inline member contributes its `properties`, those of its nested\n * `allOf` members and, for a `oneOf`/`anyOf` it carries, those of every\n * variant that declares properties inline — read through the variant's own\n * `allOf` members and nested unions the same way — tagged as the merged\n * model's own (workos/oagen#283: a variant's fields were dropped, so an\n * inline `allOf: [base, { oneOf: [{ a }, { b }] }]` lost `a` and `b` while\n * the same schema as a component kept them).\n *\n * `required` is collected from the wrapper and from every member that always\n * applies; a variant's `required` is not read, since its properties are\n * present only on that branch, so they are optional on the merged model,\n * exactly as `extractAllOfModel` flattens a component's variants. Two\n * boundaries are not crossed: a `$ref` under a variant — the variant itself,\n * or a member of the variant's own `allOf` — is not followed (its component\n * keeps its own fields), and a union a `$ref` member's component carries is\n * not read (the component's own model dispatches or flattens it).\n *\n * A property keeps the always-applying declaration `declareProperty` settles\n * on — the first that declares a type, a typeless one before or after it\n * only annotating it, two typing objects or arrays conjoined\n * (`combineDeclarations`); a declaration conjoined from two components' is\n * the merged model's own — whatever a variant says: a\n * variant can only narrow what every instance\n * carries. A property only variants declare is typed as the union of its\n * distinct declarations (`unionOfDeclarations`): one declaration, or several\n * of one shape, is that declaration; several shapes become a `oneOf` of\n * them, which the type builder reads as it reads any inline union — string\n * consts pinned differently per variant (`kind: cat` | `kind: dog`) collapse\n * to an inline enum, other literals and types to a union — so the field is\n * never typed from one variant's value alone. Properties keep the order they\n * were first declared in.\n *\n * A schema reached twice is read once in each capacity it is reached in —\n * as an inline member (the merged model's own, unions included), through a\n * `$ref` member (inherited, unions left to the component) or under a\n * variant (`required` unread, `$ref`s not followed) — and only an inline\n * reading stands for the others: a schema shared between a variant and a\n * member (a YAML anchor, an object a `transformSpec` hook reuses, a `$ref`\n * written twice) still contributes its `required` and is still followed\n * when the member is reached, and a component's own object reused as an\n * inline member still has its union read after the `$ref` reading left it\n * to the component (`done`). The walk reads property lists only — it never\n * descends into a property — so it is finite for any component graph: a\n * schema already read in the same capacity is not read again, which is what\n * stops a component that extends itself. `required` lists each name once.\n */\nexport function mergeAllOfMembers(\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): MergedAllOf {\n  const declared = new Map<string, PropertyDeclarations>();\n  const required: string[] = [];\n  const resolvedRefs: string[] = [];\n  const unresolvedRefs: string[] = [];\n  // The schemas read so far, by capacity: `inline` (an always-applying\n  // member read as the merged model's own, unions included), `inherited`\n  // (reached through a `$ref` member, its unions left to its component) and\n  // `conditional` (under a variant, `required` unread and `$ref`s not\n  // followed). An inline reading is complete, so it stands for every\n  // capacity; an inherited or conditional reading is not, so the same schema\n  // reached again in another capacity is read once more for what that\n  // capacity contributes — a component's own object reused as an inline\n  // member (an object a `transformSpec` hook shares) still has its union\n  // read, a variant's object reused as a member still has its `required`\n  // read. A schema already read in the same capacity is not read again,\n  // which is what stops a component that extends itself.\n  const done = {\n    inline: new Set<SchemaObject>(),\n    inherited: new Set<SchemaObject>(),\n    conditional: new Set<SchemaObject>(),\n  };\n  // `onBranch`: inside a `oneOf`/`anyOf` variant, whose properties are\n  // optional and whose `$ref`s are not followed.\n  const visit = (s: SchemaObject, origin: MergedProperty['origin'], onBranch: boolean): void => {\n    const capacity = onBranch ? 'conditional' : origin === null ? 'inline' : 'inherited';\n    if (done.inline.has(s) || done[capacity].has(s)) return;\n    done[capacity].add(s);\n    if (s.$ref) {\n      if (onBranch) return;\n      const rawName = s.$ref.split('/').pop() ?? '';\n      const target = componentSchemas?.[rawName];\n      const refs = target ? resolvedRefs : unresolvedRefs;\n      if (!refs.includes(s.$ref)) refs.push(s.$ref);\n      if (!target) return;\n      // The component the properties belong to is the one whose own model\n      // carries them under its name. A ref inside an `allOf` component's own\n      // chain stays that component's: its model inherits through its\n      // members, nullable ones included, and types their fields under its\n      // own name (`DogMeta`). Any other component met on the way declares\n      // nothing of its own that this reference adds to — a bare alias\n      // (`Hop: { $ref: Base }`), a nullable alias (`Alias: { oneOf: [{ $ref:\n      // Base }, { type: 'null' }] }`), a chain of either — and builds no\n      // model for the fields, so the reference starts its own origin, as a\n      // top-level ref member does (workos/oagen#308 round 4: `HolderValue.meta`\n      // named `AliasMeta`, which nothing built, where `BaseMeta` exists).\n      const owner = origin?.schema.allOf ? origin : { name: resolveSchemaName(rawName), schema: target };\n      visit(target, owner, onBranch);\n      return;\n    }\n    for (const [key, value] of Object.entries(s.properties ?? {})) {\n      if (value) declareProperty(declared, key, value, origin, onBranch);\n    }\n    if (s.required && !onBranch) for (const r of s.required) if (!required.includes(r)) required.push(r);\n    for (const sub of s.allOf ?? []) visit(sub, origin, onBranch);\n    // A nullable union wrapper — one non-null variant beside `null`, decided\n    // by `nullableUnionBranch`, the definition `unwrapNullableSchema`\n    // collapses by, which `readComponentAllOfMember` reads a component's\n    // member through and the envelope collector reads every member through\n    // (`resolveBareSchema`) — is that variant, applying as the member does:\n    // an instance that is not null is the variant, and beside an object\n    // member it is never null. So the variant is read in the member's own\n    // capacity — its `$ref` followed, its `required` read, its properties\n    // always-applying — wherever the member sits, a `$ref` member's\n    // component included (workos/oagen#308: read as a branch, `Base`'s\n    // `has_more` ended the iteration but was missing from the model). Any\n    // other inline union is flattened; one a `$ref` member's component\n    // carries belongs to that component's model.\n    const branch = nullableUnionBranch(s);\n    if (branch) visit(branch, origin, onBranch);\n    else if (origin === null) for (const variant of s.oneOf ?? s.anyOf ?? []) visit(variant, origin, true);\n  };\n  visit(schema, null, false);\n  const properties: MergedProperty[] = [...declared.values()].map(({ name, unconditional, conditional }) =>\n    unconditional\n      ? { name, schema: unconditional.schema, origin: unconditional.origin }\n      : { name, schema: unionOfDeclarations(conditional), origin: null },\n  );\n  // Limits conjoin the way properties merge, so the merged model declares what\n  // an instance must satisfy; a `$ref` member's target keeps its own limits.\n  return {\n    properties,\n    required,\n    resolvedRefs,\n    unresolvedRefs,\n    description: schema.description,\n    externalDocs: readExternalDocs(schema.externalDocs),\n    constraints: extractConstraints(schema),\n    deprecated: schema.deprecated === true || undefined,\n    extensions: extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n  };\n}\n\n/**\n * The keywords a field reads from its own schema — the flags and\n * documentation `buildFieldFromSchema` reads and the validation keywords\n * `extractConstraints` reads — which `unionOfDeclarations` lifts onto a\n * combined declaration when every declaration agrees on them.\n */\nconst LIFTED_DECLARATION_KEYWORDS: readonly string[] = [\n  'readOnly',\n  'writeOnly',\n  'deprecated',\n  'description',\n  'default',\n  'example',\n  'examples',\n  'externalDocs',\n  'minimum',\n  'maximum',\n  'exclusiveMinimum',\n  'exclusiveMaximum',\n  'multipleOf',\n  'minLength',\n  'maxLength',\n  'minItems',\n  'maxItems',\n  'minContains',\n  'maxContains',\n  'minProperties',\n  'maxProperties',\n  'pattern',\n  'uniqueItems',\n  'dependentRequired',\n];\n\n/**\n * The one schema that types a property several variants declare: the first\n * declaration when every declaration has the same shape (`schemaShapeKey`,\n * documentation ignored), else a `oneOf` of the distinct shapes, each the\n * first declaration of its shape, in order. See `mergeAllOfMembers`.\n *\n * A field reads its flags, documentation and limits from its own schema\n * (`buildFieldFromSchema`, `extractConstraints`), never from a union's\n * variants, so a combined declaration carries every keyword of\n * `LIFTED_DECLARATION_KEYWORDS` the declarations agree on, value for value:\n * two `kind` declarations both `readOnly: true` with different consts make a\n * read-only enum field; a keyword the declarations disagree on, or one only\n * some declare, is not the field's. Every declaration as written has a say,\n * a repeat of an earlier shape included. The extensions are read by the same\n * agreement (`agreedExtensions`), and — unlike the keywords, which the first\n * declaration gives when all share one shape — under both outcomes: the one\n * declaration a single shape is typed from carries the agreed keys in place\n * of its own. The declarations themselves are kept as\n * written inside the `oneOf`, so an enum member or a variant model still\n * carries its own description and limits. A `null` any declaration admits\n * (`nullable: true`, or a `type` list naming `null`) is a value the property\n * takes on that branch, so the union admits it: the admission moves to a\n * `{ type: 'null' }` variant of the `oneOf` — the one place the type builder\n * reads a union's nullability from, and one a union of string consts would\n * otherwise lose when it collapses to an enum — and off the declarations.\n */\nfunction unionOfDeclarations(declarations: readonly SchemaObject[]): SchemaObject {\n  if (declarations.length === 1) return declarations[0]!;\n  // The extensions are decided first, across every declaration as written,\n  // apart from the shape dedupe below: a declaration dropped as a repeat of\n  // an earlier shape still has its say, so `x-since` written as `1`, `2` and\n  // `1` by three declarations is nobody's (workos/oagen#369 review, which\n  // read the keys off the distinct shapes alone and kept the `1`).\n  const extensions = agreedExtensions(declarations);\n  const distinct = new Map<string, SchemaObject>();\n  for (const declaration of declarations) {\n    const key = schemaShapeKey(declaration);\n    if (!distinct.has(key)) distinct.set(key, declaration);\n  }\n  const shapes = [...distinct.values()];\n  // One shape: the first declaration, as written, carrying the agreed\n  // extensions in place of its own.\n  if (shapes.length === 1) return withAgreedExtensions(shapes[0]!, extensions);\n  // The keywords are read across every declaration the same way: a dropped\n  // repeat of a shape that disagrees on a keyword leaves it off too.\n  const agreed: Record<string, unknown> = { ...agreedDeclarationKeys(declarations, LIFTED_DECLARATION_KEYWORDS) };\n  const anyAdmitsNull = shapes.some(admitsNull);\n  const variants = anyAdmitsNull ? [...shapes.map(withoutNull), { type: 'null' }] : shapes;\n  return { ...agreed, ...extensions, oneOf: variants };\n}\n\n/**\n * The entries of `keys` every one of `declarations` declares with one\n * value — compared by `stableStringify`, so an object value agrees whatever\n * its key order — each as the first declaration writes it. A key any\n * declaration leaves unset, or declares with another value, is left out.\n * The one agreement rule for a property several variants declare, read for\n * the lifted keywords and for the extensions alike (`unionOfDeclarations`).\n */\nfunction agreedDeclarationKeys(declarations: readonly SchemaObject[], keys: Iterable<string>): Record<string, unknown> {\n  const agreed: Record<string, unknown> = {};\n  for (const key of keys) {\n    const values = declarations.map((declaration) => declaration[key]);\n    if (values[0] === undefined) continue;\n    const first = stableStringify(values[0]);\n    if (values.every((value) => value !== undefined && stableStringify(value) === first)) agreed[key] = values[0];\n  }\n  return agreed;\n}\n\n/**\n * The extensions every one of `declarations` agrees on\n * (`agreedDeclarationKeys` over the first declaration's keys, the consumed\n * ones left out as `extensionsOf` leaves them); `undefined` when none. A\n * property several variants declare carries exactly these, whether or not\n * the declarations share one shape: no one declaration is the schema for a\n * key OpenAPI gives no meaning to, and an emitter may act on it, so a key\n * the declarations dispute is nobody's.\n */\nexport function agreedExtensions(declarations: readonly SchemaObject[]): Extensions | undefined {\n  const keys = Object.keys(extensionsOf(declarations[0]!, SCHEMA_CONSUMED_EXTENSIONS) ?? {});\n  const agreed = agreedDeclarationKeys(declarations, keys);\n  return Object.keys(agreed).length > 0 ? agreed : undefined;\n}\n\n/** `schema` with `extensions` in place of its own (consumed keys kept where they are); `schema` itself when neither has any. */\nexport function withAgreedExtensions(schema: SchemaObject, extensions: Extensions | undefined): SchemaObject {\n  const own = extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS);\n  if (!own && !extensions) return schema;\n  const kept = Object.entries(schema).filter(([key]) => !(own && Object.hasOwn(own, key)));\n  return { ...Object.fromEntries(kept), ...extensions };\n}\n\n/** Whether a declaration admits `null` on its own: OAS 3.0 `nullable: true`, or a `type` list naming `null`. */\nfunction admitsNull(schema: SchemaObject): boolean {\n  return schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes('null'));\n}\n\n/** `schema` with its own `null` admission removed (see `admitsNull`); the type list collapses to its one remaining entry. */\nfunction withoutNull(schema: SchemaObject): SchemaObject {\n  const { nullable: _nullable, ...rest } = schema;\n  if (Array.isArray(rest.type)) {\n    const types = rest.type.filter((t) => t !== 'null');\n    rest.type = types.length === 1 ? types[0] : types;\n  }\n  return rest;\n}\n\n/**\n * Build the model for an inline `allOf` read as `'merged'` (`readInlineAllOf`)\n * under `name`, and materialize what its own properties reference, into\n * `results`. The model is built whatever fields the merge yields — none for\n * an `allOf` whose inline members declare only an empty `properties: {}` —\n * since the reference `schemaToTypeRef` made under the same reading exists\n * and must resolve. The model is `buildMergedModel`'s, so an inherited\n * property is typed as its component's model types it (`Base.meta` stays\n * `BaseMeta`) and is not read into again — the component pass materialized\n * whatever it references, and a component that extends itself through a\n * field (`Node.child: allOf: [{ $ref: Node }, …]`) is typed as the\n * `NodeChild` that exists instead of being re-extracted without end. Only\n * the merged model's own properties — the inline members' and the variants'\n * — are re-entered, under `name`, with the full merged property set as\n * siblings. Shared by the field extractor and `extractInlineModelDeep`, so a\n * field nested under a discriminated component variant is built exactly as\n * the same field anywhere else.\n */\nexport function materializeMergedAllOf(\n  name: string,\n  schema: SchemaObject,\n  results: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): void {\n  const merged = mergeAllOfMembers(schema, componentSchemas);\n  results.push(buildMergedModel(name, merged, componentSchemas));\n  // Properties are matched by own name throughout the merge (a `Map` there,\n  // `Object.fromEntries` here), so a property named `constructor`,\n  // `toString` or `__proto__` is kept and re-entered like any other.\n  const own = Object.fromEntries(merged.properties.filter((p) => p.origin === null).map((p) => [p.name, p.schema]));\n  const mergedSiblings = new Map(merged.properties.map((p) => [p.name, p.schema]));\n  extractInlineModelsFromProperties({ properties: own }, results, name, componentSchemas, mergedSiblings);\n}\n\n/**\n * The merged shape as one object schema, for a site that builds its model\n * from a schema rather than from the merged list (`extractDirectResource`,\n * `extractInlineModelDeep`): every property under its name in merged order,\n * the collected `required`, and the wrapper's own `deprecated`, limits and\n * link, as `buildMergedModel` carries them — a member's stay on that member,\n * a `$ref` member's on its component. The wrapper's `description` is left\n * off, as both sites left it off the schemas they rebuilt before.\n */\nexport function mergedObjectSchema(merged: MergedAllOf): SchemaObject {\n  return {\n    type: 'object',\n    properties: Object.fromEntries(merged.properties.map((p) => [p.name, p.schema])),\n    required: merged.required,\n    ...(merged.deprecated ? { deprecated: true } : {}),\n    ...merged.constraints,\n    ...(merged.externalDocs ? { externalDocs: merged.externalDocs } : {}),\n    ...merged.extensions,\n  };\n}\n\n/**\n * Build the model for a merged `allOf` field. An inherited property is typed\n * with its component as naming context and the component's own sibling set,\n * so it carries the same TypeRef as in the component's model (`BaseMeta`,\n * `BaseChild`, ...); the merged model's own properties are typed under its\n * name with the full merged property set as siblings.\n */\nfunction buildMergedModel(name: string, merged: MergedAllOf, componentSchemas?: Record<string, SchemaObject>): Model {\n  const requiredSet = new Set(merged.required);\n  const mergedSiblings = new Map(merged.properties.map((p) => [p.name, p.schema]));\n  const componentSiblings = new Map<string, Map<string, SchemaObject>>();\n  const fields = merged.properties.map((p) => {\n    if (p.origin === null) {\n      return buildFieldFromSchema(p.name, p.schema, name, requiredSet, componentSchemas, mergedSiblings);\n    }\n    let siblings = componentSiblings.get(p.origin.name);\n    if (!siblings) {\n      siblings = collectProperties(p.origin.schema, componentSchemas);\n      componentSiblings.set(p.origin.name, siblings);\n    }\n    const field = buildFieldFromSchema(p.name, p.schema, p.origin.name, requiredSet, componentSchemas, siblings);\n    // The field is a copy of the component's own: whatever inline model its\n    // references name is the one the component's field references, so they\n    // are recorded under that field and follow its model wherever it goes.\n    recordInheritedModelRefs(field.type, p.origin.name, p.name);\n    return field;\n  });\n  return {\n    name,\n    description: merged.description,\n    ...(merged.externalDocs ? { externalDocs: merged.externalDocs } : {}),\n    fields,\n    ...(merged.deprecated ? { deprecated: true } : {}),\n    ...(merged.constraints ? { constraints: merged.constraints } : {}),\n    ...(merged.extensions ? { extensions: merged.extensions } : {}),\n  };\n}\n\n/**\n * The schema that types a map's values, in the precedence `schemaToTypeRef`\n * uses: a non-empty `additionalProperties` object wins, otherwise the first\n * `patternProperties` entry. `additionalProperties: {}` means \"any value\"\n * (typed `unknown`, nothing to extract) and does not fall through to\n * `patternProperties`, matching the type-ref branch.\n */\nexport function mapValueSchema(schema: SchemaObject): SchemaObject | null {\n  const additional = schema.additionalProperties;\n  if (additional && typeof additional === 'object') {\n    return Object.keys(additional).length > 0 ? additional : null;\n  }\n  const patterns = schema.patternProperties ? Object.values(schema.patternProperties) : [];\n  return patterns[0] ?? null;\n}\n\n/**\n * The model for an inline object: its properties as fields, typed under\n * `name`, with its description and constraints. Shared with the named-union\n * extractor in schemas.ts, which materializes a union's inline object variants\n * exactly as the union branch below does.\n */\nexport function buildInlineModel(\n  name: string,\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): Model {\n  const requiredSet = new Set(schema.required ?? []);\n  const fields: Field[] = [];\n  const siblings = collectProperties(schema);\n\n  for (const [fieldName, fieldSchema] of Object.entries(schema.properties ?? {})) {\n    if (!fieldSchema) continue;\n    fields.push(buildFieldFromSchema(fieldName, fieldSchema, name, requiredSet, componentSchemas, siblings));\n  }\n\n  return {\n    name,\n    description: schema.description,\n    ...externalDocsEntry(schema.externalDocs),\n    fields,\n    ...deprecatedEntry(schema),\n    ...constraintsEntry(schema),\n    ...schemaExtensionsEntry(schema),\n  };\n}\n","import type { Model, ModelRef, Enum, EnumValue, Extensions, Field, TypeRef, Constraints } from '../ir/types.js';\nimport { walkTypeRef, collectModelTypeRefs } from '../ir/types.js';\nimport { toPascalCase, cleanSchemaName, stripListItemMarkers, splitWords } from '../utils/naming.js';\nimport { externalDocsEntry, readExternalDocs, type RawExternalDocs } from './external-docs.js';\nimport { SCHEMA_CONSUMED_EXTENSIONS, extensionsOf, schemaExtensionsEntry } from './extensions.js';\nimport {\n  enumShapeKey,\n  enumValuesOf,\n  inlineEnumDescriptionOf,\n  inlineEnumExtensionsOf,\n  inlineEnumExternalDocsOf,\n  inlineEnumRef,\n  toEnumValue,\n  type EnumMember,\n} from './enum-members.js';\n\n/**\n * Module-level transform set during extractSchemas(). Used by schemaToTypeRef()\n * to apply the same name transform to $ref model/enum references.\n *\n * Receives the cleaned PascalCase name and, when the name is a\n * `components.schemas` key, the raw key exactly as spelled in the document.\n * Names oagen synthesises (inline enums, request-body variant models,\n * title-derived names) pass no second argument.\n */\nlet activeSchemaNameTransform: SchemaNameTransform | null = null;\n\n/**\n * Module-level set of raw `components.schemas` keys for the spec being\n * extracted. resolveSchemaName() consults it to decide whether the name it was\n * handed is a real component key (forwarded to the transform as\n * `originalName`) or a name oagen synthesised (no `originalName`).\n */\nlet activeComponentSchemaKeys: Set<string> = new Set();\n\n/**\n * The document's `components/schemas`, by raw key, while they are read —\n * for a reader that resolves a `$ref` but is handed no map of its own\n * (`schemaToTypeRef`, `mintedInlineNameEntries`), so it decides exactly as\n * the extractors, which are handed the map, decide (`readInlineAllOf`).\n * Set by `extractSchemas`, cleared with the name transform.\n */\nlet activeComponentSchemas: Record<string, SchemaObject> | undefined;\n\n/** The component schema a `$ref` names, from `componentSchemas` when given, else from the document being read. */\nexport function componentSchemaOf(\n  ref: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): SchemaObject | undefined {\n  const key = ref.split('/').pop() ?? '';\n  const map = componentSchemas ?? activeComponentSchemas;\n  return map && Object.hasOwn(map, key) ? map[key] : undefined;\n}\n\n/**\n * Module-level set of resolved schema names whose components/schemas entry is\n * an enum (`isEnumComponentSchema`: an `enum:` list, or a `oneOf`/`anyOf` of\n * string consts). Populated by extractSchemas() so schemaToTypeRef()\n * can classify a `$ref` to a top-level enum schema as `kind: 'enum'` instead of\n * `kind: 'model'`. Without this, every `$ref` was naively returned as a model\n * ref, even when the target was a shared enum like `PaginationOrder`.\n */\nlet activeEnumSchemaNames: Set<string> = new Set();\n\n/**\n * Subset of `activeEnumSchemaNames` whose component schema also admits\n * `null` — via an OAS 3.1 `type: [..., 'null']` array, the OAS 3.0\n * `nullable: true` flag, or a literal `null` member in `enum:`. A `$ref` to\n * one of these resolves to `nullable(enum)` so the component's own\n * nullability survives the reference, matching the shape an inline\n * `oneOf: [{ $ref }, { type: 'null' }]` already produces.\n */\nlet activeNullableEnumSchemaNames: Set<string> = new Set();\n\n/**\n * Resolved names of named-union components that admit `null`\n * (a `type: 'null'` variant, an OAS 3.1 `type` list with `'null'`, or OAS\n * 3.0 `nullable: true`). The null variant is not a member (`namedUnionMembers`\n * drops it), so, as for a nullable enum, a `$ref` to one of these resolves to\n * `nullable(model)`: the IR then says what the inline form of the same union\n * says (`nullable<union>`).\n */\nlet activeNullableUnionSchemaNames: Set<string> = new Set();\n\n/**\n * What one extraction remembers about its named unions, so each is planned\n * once although the model (`namedUnionEntry`) and the extractor\n * (`extractNamedUnionVariantModels`) both read the plan, and so the\n * whole-document reads every plan makes — each component's shape and each\n * other union's variant names — are made once per document, not once per\n * union per read. Every entry is derived from the document being extracted\n * under `activeComponentSchemaKeys` and the active name transform, so the\n * memo is created where those are set (`extractSchemas`) and dropped with\n * them; outside an extraction nothing is memoized.\n */\ninterface NamedUnionMemo {\n  /** Each named union's plan, keyed by its schema; `name` and `schemas` are checked so a different read is never served a stale plan. */\n  plans: WeakMap<\n    SchemaObject,\n    { name: string; schemas: Record<string, SchemaObject> | undefined; plan: NamedUnionPlan | null }\n  >;\n  /** `schemaShapeKey` of every component schema and variant a plan compares, hashed once. */\n  shapes: WeakMap<SchemaObject, string>;\n  /** Each named union's inline variants named in isolation (`otherNamedUnionVariantEntries`), read by every other union's plan. */\n  variantEntries: WeakMap<SchemaObject, Map<SchemaObject, InlineVariantName>>;\n  /** `componentModelNames()`, resolved once. */\n  componentNames?: ReadonlySet<string>;\n}\nlet activeNamedUnionMemo: NamedUnionMemo | null = null;\n\n/**\n * What the parser decides about an array component (`isArrayComponentEntry`),\n * decided once per extraction and read by both sides: the reference\n * (`arrayComponentTypeRef`) and the extractor (`extractArrayComponentModels`),\n * so the items' TypeRef and the models and enums minted for them agree by\n * construction — the way a named union's plan serves `namedUnionEntry` and\n * `extractNamedUnionVariantModels`.\n */\ninterface ArrayComponentPlan {\n  /** The `components/schemas` key, as written: what a `$ref` names. */\n  key: string;\n  /** The key's IR name (`resolveSchemaName`): what the items are named from. */\n  name: string;\n  /** The component schema as written. */\n  schema: SchemaObject;\n  /**\n   * The synthetic property the schema is typed and extracted as, under the\n   * component's name: `item`, so the items mint `<Component>Item…`, or the\n   * context the tree stepped to (`item_item`, `item_array_item`, numbered)\n   * when a name it would mint anywhere — the item model, an object nested\n   * under it, an inline enum, a union variant — is already a component's,\n   * another array component's tree's, or another named union's inline\n   * variant's, of a different shape (`planArrayComponent`).\n   */\n  context: string;\n  /** `{ [context]: schema }`: the one-property object both sides read, as a named union's `memberProperties`. */\n  properties: ReadonlyMap<string, SchemaObject>;\n  /** Set once the self-reference warning has been printed, so it is printed once per component. */\n  warnedSelfReference: boolean;\n}\n\n/** Every model and inline enum an array component's item tree mints under one context (`arrayComponentMints`). */\ninterface ArrayComponentMints {\n  models: Model[];\n  /** Each inline enum the items are or hold, by name, with its members. */\n  enums: Map<string, EnumValue[]>;\n}\n\n/**\n * Every array component of the document being extracted, by its\n * `components/schemas` key as written — the key a `$ref` names, so `Notes:\n * { type: array, items: { $ref: Note } }` beside `Note: { type: object }`,\n * two keys `cleanSchemaName` resolves to one name, keep `Note` a model and\n * make `$ref: Notes` the array. Such a component becomes no `Model`; a\n * `$ref` to it resolves to the array itself, and what its items reference\n * is extracted under its resolved name. Planned in `extractSchemas` before\n * any TypeRef is built, because the component loop, the field pass, the\n * operations and the webhooks all resolve references to it, and dropped\n * with the other per-document state (`clearSchemaNameTransform`): outside\n * an extraction a `$ref` to such a key is a plain model reference, as a\n * `$ref` to an enum component is.\n */\nlet activeArrayComponentPlans: Map<string, ArrayComponentPlan> = new Map();\n\n/** The array components whose reference is being built right now, so a cycle through their items is cut (`arrayComponentTypeRef`). */\nconst resolvingArrayComponents = new Set<string>();\n\n/** Drop `null` from an `enum:` list — it marks nullability, it is not a member. */\nfunction nonNullEnumValues(values: SchemaObject['enum']): (string | number)[] {\n  return (values ?? []).filter((v): v is string | number => v !== null);\n}\n\n/**\n * True when an enum schema admits `null` by any OAS 3.0 / 3.1 spelling: the\n * `nullable: true` flag, a `type` list naming `'null'`, a `null` member in\n * `enum:`, or — for an enum declared as a `oneOf`/`anyOf` of `const`\n * schemas — a `type: 'null'` variant that an `enum:` list beside the union\n * does not forbid (`enumListAdmitsNull`).\n */\nfunction isNullableEnumSchema(schema: SchemaObject): boolean {\n  if (schema.nullable === true) return true;\n  if (Array.isArray(schema.type) && schema.type.includes('null')) return true;\n  if (Array.isArray(schema.enum) && schema.enum.includes(null)) return true;\n  return (schema.oneOf ?? schema.anyOf ?? []).some(isNullVariantSchema) && enumListAdmitsNull(schema);\n}\n\n/**\n * Whether an `enum:` list written beside a `oneOf`/`anyOf` of consts lets a\n * `type: 'null'` variant admit `null`. The keywords apply together, so a\n * list that leaves `null` out forbids it whatever the variant says; a schema\n * with no list admits it.\n */\nfunction enumListAdmitsNull(schema: SchemaObject): boolean {\n  return !Array.isArray(schema.enum) || schema.enum.includes(null);\n}\n\n/**\n * Whether a component schema is an enum: it declares an `enum:` list, or it\n * is a `oneOf`/`anyOf` whose every non-null variant is a string `const`\n * schema (`constUnionEnumMembers`) with no `allOf` and no `properties` of\n * its own — the OAS 3.1 spelling that documents and deprecates values one\n * by one. Both become an `Enum` (`extractEnum`), and a `$ref` to either\n * resolves to an `EnumRef`; the same `oneOf` written inline collapses to an\n * inline enum (`schemaToTypeRef`), so the two spellings have one shape\n * wherever they appear. A `oneOf` with any other variant — a `$ref`, an\n * object, a number const — is a named union, as before.\n */\nfunction isEnumComponentSchema(schema: SchemaObject): boolean {\n  return Boolean(schema.enum) || isConstUnionEnumSchema(schema);\n}\n\n/** The `oneOf`/`anyOf`-of-string-consts half of `isEnumComponentSchema`. */\nfunction isConstUnionEnumSchema(schema: SchemaObject): boolean {\n  if (schema.allOf || Object.keys(schema.properties ?? {}).length > 0) return false;\n  return constUnionEnumMembers(schema) !== null;\n}\n\n/**\n * `{ description }` holding the first of `candidates` that is a string with\n * non-whitespace content, `{}` when none is — spread into an `EnumMember`.\n */\nfunction descriptionEntry(...candidates: unknown[]): { description?: string } {\n  const text = candidates.find((raw) => typeof raw === 'string' && raw.trim() !== '');\n  return typeof text === 'string' ? { description: text } : {};\n}\n\n/**\n * The members of an enum schema in document order, each with the\n * documentation the document attaches to that one value, from whichever\n * spelling declares them: a `oneOf`/`anyOf` of string `const` schemas\n * (`constUnionEnumMembers`, an `enum:` list beside it restricting the\n * members) first, else an `enum:` list alone (`enumListMembers`). Null when\n * the schema is neither.\n */\nexport function enumMembersOf(schema: SchemaObject): EnumMember[] | null {\n  return constUnionEnumMembers(schema) ?? enumListMembers(schema);\n}\n\n/**\n * The members an `enum:` list declares: each non-null entry (a `null` marks\n * nullability, `isNullableEnumSchema`), a number kept as one and anything\n * else as its string form, described by the schema's `x-enum-descriptions`\n * / `x-enumDescriptions` entry for it (`enumValueDescriptions`). No entry\n * is deprecated: an `enum:` list has no per-value keyword. Null when the\n * schema declares no `enum:`.\n */\nfunction enumListMembers(schema: SchemaObject): EnumMember[] | null {\n  if (!schema.enum) return null;\n  const describe = enumValueDescriptions(schema);\n  const members: EnumMember[] = [];\n  schema.enum.forEach((raw, index) => {\n    if (raw === null) return;\n    const value = typeof raw === 'number' ? raw : String(raw);\n    members.push({ value, ...descriptionEntry(describe(value, index)) });\n  });\n  return members;\n}\n\n/**\n * The members a `oneOf`/`anyOf` of string `const` schemas declares — a\n * single-member string `enum` is the same thing — once its `type: 'null'`\n * variants are set aside: each variant's `const`, with the variant's own\n * `description` and, when it says `deprecated: true`, `deprecated` (the\n * literal `true` only, as `deprecatedEntry` reads it everywhere). A member\n * whose own `description` has no content takes the schema's\n * `x-enum-descriptions` / `x-enumDescriptions` entry for it\n * (`enumValueDescriptions`), the list form read at the variant's position as\n * written. An `enum:` list written beside the union applies together with\n * it, as JSON Schema keywords do: a member whose value the list leaves out\n * is dropped (so the list may leave no member at all), and the list decides\n * whether a `type: 'null'` variant admits `null` (`enumListAdmitsNull`).\n * Null when the schema has no `oneOf`/`anyOf`, when every variant is\n * `type: 'null'`, or when any variant is anything but a string const — a\n * `$ref`, an object, a number const — since such a union is not an enum.\n */\nfunction constUnionEnumMembers(schema: SchemaObject): EnumMember[] | null {\n  const variants = (schema.oneOf ?? schema.anyOf)\n    ?.map((variant, index) => ({ variant, index }))\n    .filter(({ variant }) => !isNullVariantSchema(variant));\n  if (!variants || variants.length === 0) return null;\n  const allowed = schema.enum\n    ? new Set(nonNullEnumValues(schema.enum).map((v) => (typeof v === 'number' ? v : String(v))))\n    : undefined;\n  const describe = enumValueDescriptions(schema);\n  const members: EnumMember[] = [];\n  for (const { variant, index } of variants) {\n    const value =\n      typeof variant.const === 'string'\n        ? variant.const\n        : Array.isArray(variant.enum) && variant.enum.length === 1 && typeof variant.enum[0] === 'string'\n          ? variant.enum[0]\n          : undefined;\n    if (value === undefined) return null;\n    if (allowed && !allowed.has(value)) continue;\n    members.push({\n      value,\n      ...descriptionEntry(variant.description, describe(value, index)),\n      ...deprecatedEntry(variant),\n    });\n  }\n  return members;\n}\n\n/**\n * The per-value descriptions an enum schema's `x-enum-descriptions` or\n * `x-enumDescriptions` extension declares, as a lookup by value and position.\n * Either key may hold an object mapping each value's text form (`\"5\"` for a\n * numeric `5`) to its description, or a list aligned with the members as\n * written — the `enum:` entries, or the `oneOf`/`anyOf` variants, a `null`\n * entry or `type: 'null'` variant counted in its place. `x-enum-descriptions`\n * is read when it holds an object or a list, `x-enumDescriptions` otherwise;\n * an entry that is not a string with non-whitespace content, or a value with\n * no entry, describes nothing (`descriptionEntry`).\n */\nfunction enumValueDescriptions(schema: SchemaObject): (value: string | number, index: number) => unknown {\n  const raw = [schema['x-enum-descriptions'], schema['x-enumDescriptions']].find(\n    (candidate) => typeof candidate === 'object' && candidate !== null,\n  );\n  if (raw === undefined) return () => undefined;\n  if (Array.isArray(raw)) return (_value, index) => raw[index];\n  const byValue = raw as Record<string, unknown>;\n  return (value) => (Object.hasOwn(byValue, String(value)) ? byValue[String(value)] : undefined);\n}\n\n/** Wrap `ref` in `nullable` unless it already is one, so a nullable enum `$ref` is never double-wrapped. */\nfunction asNullable(ref: TypeRef): TypeRef {\n  return ref.kind === 'nullable' ? ref : { kind: 'nullable', inner: ref };\n}\n\n/**\n * Apply cleanSchemaName + the active transform (if any) to a raw schema name.\n * When `rawName` is a `components.schemas` key the transform also receives it\n * as `originalName`, so a consumer can opt out of normalization by returning\n * the original spelling. Names oagen synthesises (request-body variant\n * models, title-derived names, ...) are not component keys and get no\n * `originalName`.\n */\nexport function resolveSchemaName(rawName: string): string {\n  let name = cleanSchemaName(toPascalCase(rawName));\n  if (activeSchemaNameTransform) {\n    const originalName = activeComponentSchemaKeys.has(rawName) ? rawName : undefined;\n    name = activeSchemaNameTransform(name, originalName);\n  }\n  return name;\n}\n\n/**\n * Signature of the `schemaNameTransform` hook. `name` is the cleaned\n * PascalCase name; `originalName` is the `components.schemas` key exactly\n * as spelled in the document, or `undefined` for names oagen synthesises.\n * See `SchemaExtractionOptions.schemaNameTransform`.\n */\nexport type SchemaNameTransform = (name: string, originalName?: string) => string;\n\nexport interface SchemaExtractionOptions {\n  /**\n   * Custom transform for schema (model/enum) names. Called with the cleaned\n   * PascalCase name and, for component schemas, the original name as spelled\n   * in the document (`originalName`). Returning `originalName` opts that\n   * schema out of the built-in normalization; only do so when it is a valid\n   * identifier, since keys like `user-profile` are otherwise fixed by\n   * cleanSchemaName. `originalName` is undefined for\n   * any name oagen synthesises (inline enums, request-body variant models,\n   * title-derived names).\n   */\n  schemaNameTransform?: SchemaNameTransform;\n  /**\n   * The whole OpenAPI document the schemas come from, read once up front for\n   * the rules that look at every inline schema of a root at a time: a\n   * title-mapped union variant keeps its bare title only when no variant of\n   * another shape takes the same title under the same root\n   * (`markContestedTitles`). Without it, the component schemas are the only\n   * root, so a title a request body, response, header, parameter or webhook\n   * payload repeats with another shape is not seen.\n   */\n  document?: unknown;\n}\n\nexport interface SchemaObject {\n  type?: string | string[];\n  format?: string;\n  description?: string;\n  properties?: Record<string, SchemaObject | undefined>;\n  required?: string[];\n  items?: SchemaObject;\n  /** OAS 3.1 allows a literal `null` member when `type` also admits null. */\n  enum?: (string | number | null)[];\n  allOf?: SchemaObject[];\n  oneOf?: SchemaObject[];\n  anyOf?: SchemaObject[];\n  discriminator?: { propertyName: string; mapping?: Record<string, string> };\n  readOnly?: boolean;\n  writeOnly?: boolean;\n  nullable?: boolean;\n  $ref?: string;\n  additionalProperties?: boolean | SchemaObject;\n  const?: unknown;\n  patternProperties?: Record<string, SchemaObject>;\n  deprecated?: boolean;\n  default?: unknown;\n  example?: unknown;\n  /** JSON Schema `examples` list; OAS 3.1 deprecates `example` in its favour. */\n  examples?: unknown[];\n  /** An External Documentation Object as written; `readExternalDocs` decides what reaches the IR. */\n  externalDocs?: RawExternalDocs;\n  // JSON Schema validation vocabulary. An exclusive bound is the bound itself\n  // in OAS 3.1 and, in OAS 3.0, a boolean that makes `minimum` / `maximum`\n  // exclusive; extractConstraints() normalizes both to the 3.1 shape.\n  minimum?: number;\n  maximum?: number;\n  exclusiveMinimum?: number | boolean;\n  exclusiveMaximum?: number | boolean;\n  multipleOf?: number;\n  minLength?: number;\n  maxLength?: number;\n  pattern?: string;\n  minItems?: number;\n  maxItems?: number;\n  uniqueItems?: boolean;\n  minContains?: number;\n  maxContains?: number;\n  minProperties?: number;\n  maxProperties?: number;\n  dependentRequired?: Record<string, string[]>;\n  [key: string]: unknown;\n}\n\n/** Validation keywords copied through unchanged when they hold a number. */\nconst NUMERIC_CONSTRAINT_KEYS = [\n  'multipleOf',\n  'minLength',\n  'maxLength',\n  'minItems',\n  'maxItems',\n  'minContains',\n  'maxContains',\n  'minProperties',\n  'maxProperties',\n] as const;\n\n/**\n * Collect the JSON Schema validation keywords declared directly on `schema`\n * into a `Constraints` object, or `undefined` when it declares none — so a\n * schema without limits yields no `constraints` key on its IR node at all.\n *\n * Numeric bounds are normalized to the OAS 3.1 shape. OAS 3.0 spells an\n * exclusive bound as `exclusiveMinimum: true` beside `minimum: n`; that pair\n * becomes `exclusiveMinimum: n` with no `minimum`. A boolean `false`, or a\n * `true` with no bound to apply to, is dropped. The 3.1 numeric form passes\n * through, including the legal-but-unusual case of both an inclusive and an\n * exclusive bound on the same side. `uniqueItems: false` restates the default\n * and is dropped too.\n *\n * Only the schema's own keywords are read: limits nested inside array `items`\n * or map values are not collected. The one exception is a nullable wrapper —\n * a `oneOf`/`anyOf` with a single non-null, non-`$ref` branch — that declares\n * none itself: it takes that branch's keywords, since the IR collapses it to\n * `nullable<T>`. Values of the wrong type (a string `maxLength`, say) are\n * ignored rather than carried.\n */\nexport function extractConstraints(schema: SchemaObject): Constraints | undefined {\n  // The schema's own keywords conjoined with its `allOf` members' (recursively;\n  // a keyword declared at more than one level is combined by\n  // combineConstraints, so the stricter bound wins). schemaToTypeRef unwraps a\n  // single-member `allOf`, so `{ allOf: [{ type: 'string', maxLength: 3 }] }`\n  // is a string whose limit is the value's own; a `$ref` member contributes\n  // the keywords written beside the reference, but the target itself is not\n  // followed — its limits stay on the referenced model.\n  let out = ownConstraints(schema);\n  for (const member of schema.allOf ?? []) out = combineConstraints(out, extractConstraints(member));\n  // A nullable wrapper — `oneOf`/`anyOf` with exactly one non-null branch —\n  // collapses to `nullable<T>` in the IR, so that branch's keywords are the\n  // value's own too and conjoin with the rest. A `$ref` branch keeps its\n  // limits on the referenced model, and a genuine multi-variant union carries\n  // none.\n  const branch = singleNonNullBranch(schema);\n  return branch ? combineConstraints(out, extractConstraints(branch)) : out;\n}\n\n/** The keywords declared strictly on `schema`, normalized — without the nullable-branch fallback. */\nfunction ownConstraints(schema: SchemaObject): Constraints | undefined {\n  const out: Constraints = {};\n\n  const lower = normalizeBound(schema.minimum, schema.exclusiveMinimum);\n  if (lower.inclusive !== undefined) out.minimum = lower.inclusive;\n  if (lower.exclusive !== undefined) out.exclusiveMinimum = lower.exclusive;\n  const upper = normalizeBound(schema.maximum, schema.exclusiveMaximum);\n  if (upper.inclusive !== undefined) out.maximum = upper.inclusive;\n  if (upper.exclusive !== undefined) out.exclusiveMaximum = upper.exclusive;\n\n  for (const key of NUMERIC_CONSTRAINT_KEYS) {\n    const value = schema[key];\n    if (typeof value === 'number') out[key] = value;\n  }\n  if (typeof schema.pattern === 'string') out.pattern = schema.pattern;\n  if (schema.uniqueItems === true) out.uniqueItems = true;\n\n  const dependentRequired = readDependentRequired(schema.dependentRequired);\n  if (dependentRequired) out.dependentRequired = dependentRequired;\n  return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** The one non-null, non-`$ref` branch of a `oneOf`/`anyOf`, or `undefined` for anything else. */\nfunction singleNonNullBranch(schema: SchemaObject): SchemaObject | undefined {\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (!variants) return undefined;\n  const nonNull = variants.filter((v) => !isNullSchema(v));\n  return nonNull.length === 1 && !nonNull[0].$ref ? nonNull[0] : undefined;\n}\n\n/** True for the `{ type: 'null' }` / `{ type: ['null'] }` branch of a nullable wrapper. */\nexport function isNullSchema(schema: SchemaObject): boolean {\n  return (\n    schema.type === 'null' || (Array.isArray(schema.type) && schema.type.length === 1 && schema.type[0] === 'null')\n  );\n}\n\n/**\n * `{ constraints }` when `schema` declares any validation keyword, `{}`\n * otherwise — spread into an IR node so the key stays absent rather than\n * present-but-undefined.\n */\nexport function constraintsEntry(schema: SchemaObject): { constraints?: Constraints } {\n  const constraints = extractConstraints(schema);\n  return constraints ? { constraints } : {};\n}\n\n/**\n * `{ deprecated: true }` when `schema` says so, `{}` otherwise — spread into\n * a Model or Enum so the key stays absent rather than present-but-false. Read\n * the way `Field.deprecated` is: only the schema's own top-level keyword, and\n * only the literal `true` — `deprecated: \"yes\"` is not a declaration, as it\n * is not on a field, parameter, operation or header.\n */\nexport function deprecatedEntry(schema: SchemaObject): { deprecated?: boolean } {\n  return schema.deprecated === true ? { deprecated: true } : {};\n}\n\n/**\n * Strip the nullable wrappers `schemaToTypeRef` unwraps before it names\n * anything — the OAS 3.1 `type: [X, 'null']` array, the OAS 3.0\n * `nullable: true` flag, and a `oneOf`/`anyOf` with a single non-null\n * variant — so extraction dispatches on the same shape the TypeRef was built\n * from. The unwrap keeps `contextName`/`parentModelName` semantics intact:\n * `schemaToTypeRef` passes both through each of these wrappers unchanged.\n *\n * `carry` is applied at each union level, to the branch with the wrapper\n * it collapses from, before the branch is unwrapped in turn — so a caller\n * that builds a model from the result (`unwrapNullableField`) composes the\n * wrappers' documentation outermost-first through every level\n * (`withWrapperDocs`). The default keeps the branch as written, which is\n * what every site that only dispatches on the unwrapped shape needs. The\n * type-array and `nullable: true` forms unwrap by spreading, so every\n * keyword of theirs survives without it.\n */\nexport function unwrapNullableSchema(\n  schema: SchemaObject,\n  carry: (branch: SchemaObject, wrapper: SchemaObject) => SchemaObject = (branch) => branch,\n): SchemaObject {\n  if (schema.$ref) return schema;\n  // `properties` beside a typing composition are folded into it before any\n  // wrapper is stripped (`foldSiblingProperties`), so a nullable union\n  // written beside them collapses onto a variant that already carries them,\n  // and every site dispatches on the one shape `schemaToTypeRef` typed.\n  const folded = foldSiblingProperties(schema);\n  if (Array.isArray(folded.type)) {\n    const nonNullTypes = folded.type.filter((t) => t !== 'null');\n    if (nonNullTypes.length !== 1) return folded;\n    return unwrapNullableSchema({ ...folded, type: nonNullTypes[0], nullable: false }, carry);\n  }\n  if (folded.nullable && folded.type) {\n    return unwrapNullableSchema({ ...folded, nullable: false }, carry);\n  }\n  // A nullable union collapses onto its one non-null variant — decided by\n  // `nullableUnionBranch`, the same definition `collapsedNullableBranch`\n  // checks, so the check and the unwrap cannot disagree.\n  const branch = nullableUnionBranch(folded);\n  return branch ? unwrapNullableSchema(carry(branch, folded), carry) : folded;\n}\n\n/**\n * The one variant a nullable `oneOf`/`anyOf` wrapper collapses to: what is\n * left once every `null` variant (`isNullSchema` — `{ type: 'null' }` or\n * `{ type: ['null'] }`, however many of either) is discarded, when at least\n * one was and exactly one variant remains. The single definition of a\n * nullable union wrapper on the model side, shared by `unwrapNullableSchema`\n * and `collapsedNullableBranch`. `undefined` otherwise: no union, a union\n * under `allOf` (which `schemaToTypeRef` gives precedence), no `null`\n * variant, or more than one non-null variant. Exported for the response\n * path, which wraps an array it builds itself in `nullable` exactly when\n * `schemaToTypeRef` would (`nullableIf`).\n */\nexport function nullableUnionBranch(schema: SchemaObject): SchemaObject | undefined {\n  const variants = schema.allOf ? undefined : (schema.oneOf ?? schema.anyOf);\n  if (!variants) return undefined;\n  const nonNull = variants.filter((v) => !isNullSchema(v));\n  return nonNull.length === 1 && nonNull.length < variants.length ? nonNull[0] : undefined;\n}\n\n/**\n * The array schema `schema` is, once a nullable wrapper of any spelling is\n * removed — an OAS 3.1 type list naming `null` (`type: ['array', 'null']`),\n * OAS 3.0 `nullable: true`, or a `oneOf`/`anyOf` with one non-null variant,\n * written with or without `items` beside it — and `undefined` when it is\n * not an array: `unwrapNullableSchema`, the one definition the model side\n * unwraps by, then `isArraySchema`, the one test every site makes. So a\n * list envelope's data array, an array response body and an `allOf`-merged\n * array property are arrays here whatever wrapper they wear, as\n * `schemaToTypeRef` types them `nullable<array<…>>`. A `$ref` is a reference\n * and is not looked through: a `$ref` to an array component is typed as the\n * array the component declares by `schemaToTypeRef` itself, with the items\n * the component pass built (`isArrayComponentRef` says whether a property\n * is one), and the explicit `dataPath` walk (`resolveBareSchema`) is the one\n * place any other reference is followed.\n */\nexport function arraySchemaOf(schema: SchemaObject): SchemaObject | undefined {\n  const bare = unwrapNullableSchema(schema);\n  return isArraySchema(bare) ? bare : undefined;\n}\n\n/**\n * Whether `schemaToTypeRef` wraps the schema's own type in `nullable`: an OAS\n * 3.1 type list naming `null` (`type: ['array', 'null']`), an OAS 3.0\n * `nullable: true` beside a `type`, or a `oneOf`/`anyOf` that collapses to\n * one non-null variant (`nullableUnionBranch`). The one test for the places\n * the response path builds an array TypeRef itself (`nullableIf`) or merges\n * two array declarations (`combineDeclarations`).\n */\nexport function declaresNull(schema: SchemaObject): boolean {\n  return (\n    (Array.isArray(schema.type) && schema.type.includes('null')) ||\n    (schema.nullable === true && schema.type !== undefined) ||\n    nullableUnionBranch(schema) !== undefined\n  );\n}\n\n/**\n * `unwrapNullableSchema` for a schema a model is built from, carrying the\n * wrappers' limits, the outermost's `deprecated` and every collapsed\n * level's documentation onto the branch it unwraps to. The type-array and\n * `nullable: true` forms unwrap by spreading, so every keyword survives;\n * the union form swaps in the bare branch, which would drop a\n * `minProperties` or `deprecated: true` written beside\n * `anyOf: [{ type: 'object', … }, { type: 'null' }]`. `extractConstraints`\n * conjoins each wrapper's own keywords with its branch's as the field's\n * limits, and `Field.deprecated` is the outermost wrapper's, so the model\n * built from the branch must carry the same ones or it would disagree with\n * its field; the documentation — text, link, examples, extensions — rides\n * along level by level, outermost first, by the one wrapper rule\n * (`withWrapperDocs`, applied by `unwrapNullableSchema` at each level). Every\n * extractor that builds a model from a nullable wrapper's branch — the field\n * extractor, `extractNestedSchema`, `extractInlineModelDeep`, the request-body\n * and wrapped-response paths — goes through this one function, so the\n * copies they produce agree and the inline-model merges cannot keep a wrongly\n * flagged one. Returns `schema` itself when there is nothing to unwrap, and a\n * copy whenever a wrapper was stripped — a copy that still carries the union\n * when a multi-variant `oneOf`/`anyOf` sits beside `type: [X, 'null']`, so\n * identity with `schema` does not tell whether a union collapsed to one\n * branch; `collapsedNullableBranch` does.\n */\nexport function unwrapNullableField(schema: SchemaObject): SchemaObject {\n  // The documentation of every collapsed level rides onto the branch as it\n  // is unwrapped, outermost first (`withWrapperDocs` through\n  // `unwrapNullableSchema`), so an inner wrapper's text, link or key reaches\n  // the model wherever the outer has none; the limits conjoin through every\n  // level too (`extractConstraints`), and the flag is the outermost\n  // wrapper's alone, as `Field.deprecated` reads it.\n  const inner = unwrapNullableSchema(schema, withWrapperDocs);\n  if (inner === schema || schema.allOf || !(schema.oneOf ?? schema.anyOf)) return inner;\n  return withWrapperDeprecation({ ...inner, ...extractConstraints(schema) }, schema);\n}\n\n/**\n * The one branch a nullable `oneOf`/`anyOf` wrapper collapses to, carrying\n * the wrapper's `deprecated` and limits (`unwrapNullableField`), or\n * `undefined` when `schema` is not such a wrapper: not a union, or a union\n * with more than one non-null variant — nullable or not, including\n * `type: ['object', 'null']` beside a multi-variant `oneOf`. Decided at the\n * wrapper's level alone, by `nullableUnionBranch` — the very definition\n * `unwrapNullableSchema` collapses by, so the check and the unwrap cannot\n * disagree: the union collapses iff discarding every `null` variant, however\n * many and however spelled, leaves exactly one, whatever that variant\n * contains — a branch's own nested `oneOf`/`anyOf` (a union of constraint\n * sets beside its properties, say) is the branch's business and is built as\n * written, flag and limits carried. A multi-variant union is never\n * collapsed: each variant is its own schema, built as itself with its own\n * flag, and the wrapper's stays on the field. The sites that build a model\n * from a union's variants substitute the branch this returns for the one\n * variant it stands for, and otherwise build every variant as written.\n */\nexport function collapsedNullableBranch(schema: SchemaObject): SchemaObject | undefined {\n  return nullableUnionBranch(schema) ? unwrapNullableField(schema) : undefined;\n}\n\n/**\n * `inner` carrying the wrapper's `deprecated` in place of its own. A wrapper\n * the parser collapses — a nullable `oneOf`/`anyOf`, a single-member `allOf`\n * — is the field's schema, and `Field.deprecated` reads only that top-level\n * keyword, so the model built from what it unwraps to carries the same flag\n * the field does: the wrapper's, never the branch's or the member's own.\n */\nexport function withWrapperDeprecation(inner: SchemaObject, wrapper: SchemaObject): SchemaObject {\n  const result: SchemaObject = { ...inner, ...deprecatedEntry(wrapper) };\n  if (wrapper.deprecated !== true) delete result.deprecated;\n  return result;\n}\n\n/**\n * `inner` carrying the wrapper's documentation layer — every keyword that\n * documents a schema without shaping it, the schema-side counterpart of a\n * Field's documentation (`FIELD_DOC_KEYS` in inline-models.ts): its\n * `description` when it has non-whitespace content (as `inlineEnumRef` and\n * `Model.description` read text), its `externalDocs` when usable\n * (`readExternalDocs`), its `example` when the key is present (an explicit\n * `null` is a value, as `Field.example` keeps it), its `examples` when a\n * non-empty list, and its `x-*` keys one by one (`extensionsOf`, the\n * consumed keys left where they are read). The wrapper's value wins\n * wherever both declare one; the branch keeps its own where the wrapper\n * has none; `inner` itself comes back when the wrapper carries nothing.\n *\n * The one rule for a wrapper the parser collapses — a nullable\n * `oneOf`/`anyOf`, a single-member `allOf` — which is the schema the\n * document wrote for the property, parameter, header or body, so what it\n * unwraps to must document itself by the wrapper first. Applied at every\n * collapse step, so nested wrappers compose outermost-first: an outer\n * wrapper's keys land on the inner wrapper before the inner wrapper's land\n * on the branch, and an inner wrapper's key survives wherever the outer has\n * none (workos/oagen#369 round 3: the model path restored the outermost\n * wrapper's keys after unwrapping every level at once, so an inner\n * wrapper's were lost). Read by the type builder's two wrapper sites\n * (`schemaToTypeRef`), by the model extractors (`unwrapNullableField`\n * through `unwrapNullableSchema`, `unwrappedAllOfMember`) and by the\n * response path (`extractDirectResource`), so a model, an enum and a field\n * built from one wrapper document themselves alike.\n */\nexport function withWrapperDocs(inner: SchemaObject, wrapper: SchemaObject): SchemaObject {\n  const carried: SchemaObject = {};\n  if (typeof wrapper.description === 'string' && wrapper.description.trim() !== '') {\n    carried.description = wrapper.description;\n  }\n  const externalDocs = readExternalDocs(wrapper.externalDocs);\n  if (externalDocs) carried.externalDocs = wrapper.externalDocs;\n  if (Object.hasOwn(wrapper, 'example')) carried.example = wrapper.example;\n  if (Array.isArray(wrapper.examples) && wrapper.examples.length > 0) carried.examples = wrapper.examples;\n  Object.assign(carried, extensionsOf(wrapper, SCHEMA_CONSUMED_EXTENSIONS));\n  return Object.keys(carried).length === 0 ? inner : { ...inner, ...carried };\n}\n\n/** Keywords where the stricter of two declarations is the larger value. */\nconst MIN_KEYS = ['minimum', 'exclusiveMinimum', 'minLength', 'minItems', 'minContains', 'minProperties'] as const;\n/** Keywords where the stricter of two declarations is the smaller value. */\nconst MAX_KEYS = ['maximum', 'exclusiveMaximum', 'maxLength', 'maxItems', 'maxContains', 'maxProperties'] as const;\n\n/**\n * Conjoin two constraint sets the way `allOf` conjoins schemas: an instance\n * must satisfy both, so every `min*` takes the larger value, every `max*` the\n * smaller, `uniqueItems` holds if either side demands it, and\n * `dependentRequired` merges per property with the union of its names\n * (deduplicated, `a`'s order first). A keyword declared on one side only is\n * kept as is, and an absent side yields the other unchanged.\n *\n * `multipleOf` and `pattern` keep `a`'s value when the two differ: a true\n * conjunction would need the least common multiple, or a lookahead regex\n * joining both patterns, and neither is worth carrying into the IR.\n *\n * Not for the parameter `$ref` fallback in extractParams: keywords written\n * beside a `$ref` override the target's there, which is a different operation.\n */\nexport function combineConstraints(a: Constraints | undefined, b: Constraints | undefined): Constraints | undefined {\n  if (!a) return b;\n  if (!b) return a;\n  const out: Constraints = { ...a, ...b };\n  for (const key of MIN_KEYS) {\n    const [x, y] = [a[key], b[key]];\n    if (x !== undefined && y !== undefined) out[key] = Math.max(x, y);\n  }\n  for (const key of MAX_KEYS) {\n    const [x, y] = [a[key], b[key]];\n    if (x !== undefined && y !== undefined) out[key] = Math.min(x, y);\n  }\n  if (a.uniqueItems || b.uniqueItems) out.uniqueItems = true;\n  if (a.multipleOf !== undefined && b.multipleOf !== undefined) out.multipleOf = a.multipleOf;\n  if (a.pattern !== undefined && b.pattern !== undefined) out.pattern = a.pattern;\n  if (a.dependentRequired && b.dependentRequired) {\n    out.dependentRequired = unionDependentRequired(a.dependentRequired, b.dependentRequired);\n  }\n  return out;\n}\n\n/** Per-property union of two `dependentRequired` maps, deduplicated and keeping `a`'s order first. */\nfunction unionDependentRequired(a: Record<string, string[]>, b: Record<string, string[]>): Record<string, string[]> {\n  const merged = new Map<string, string[]>();\n  for (const [property, names] of Object.entries(a)) merged.set(property, [...names]);\n  for (const [property, names] of Object.entries(b)) {\n    const existing = merged.get(property);\n    if (!existing) {\n      merged.set(property, [...names]);\n      continue;\n    }\n    for (const name of names) if (!existing.includes(name)) existing.push(name);\n  }\n  return Object.fromEntries(merged);\n}\n\n/**\n * Resolve one side's bound from `minimum` / `maximum` plus its `exclusive*`\n * companion into the OAS 3.1 shape: a numeric companion is the exclusive\n * bound itself, `true` turns the inclusive bound into the exclusive one, and\n * `false` or absent leaves the inclusive bound as is.\n */\nfunction normalizeBound(inclusive: unknown, exclusive: unknown): { inclusive?: number; exclusive?: number } {\n  const bound = typeof inclusive === 'number' ? inclusive : undefined;\n  if (typeof exclusive === 'number') return { inclusive: bound, exclusive };\n  if (exclusive === true) return { exclusive: bound };\n  return { inclusive: bound };\n}\n\n/** Copy `dependentRequired` when it is an object whose values are string arrays; anything else is ignored. */\nfunction readDependentRequired(value: unknown): Record<string, string[]> | undefined {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n  const entries: [string, string[]][] = [];\n  for (const [property, deps] of Object.entries(value as Record<string, unknown>)) {\n    if (Array.isArray(deps) && deps.every((d): d is string => typeof d === 'string'))\n      entries.push([property, [...deps]]);\n  }\n  // Object.fromEntries creates an own property for every key. Assigning\n  // `out[property]` on a literal would instead set the prototype for a\n  // dependency named `__proto__` and silently drop it.\n  return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\n/**\n * Narrow a raw `examples` value to a non-empty list, or undefined. Guards\n * against documents that put an OAS Example Object map (or anything else)\n * where JSON Schema expects an array, and against an empty list, so the IR\n * carries `examples` only when there is at least one value.\n */\nexport function nonEmptyExamples(value: unknown): unknown[] | undefined {\n  return Array.isArray(value) && value.length > 0 ? value : undefined;\n}\n\n/**\n * Pick the single `example` the IR carries: the document's own `example`\n * when it is set (including an explicit `null`), otherwise the first entry\n * of the resolved `examples` list.\n */\nexport function pickExample(example: unknown, examples: unknown[] | undefined): unknown {\n  return example !== undefined ? example : examples?.[0];\n}\n\n/** One source of example values, e.g. a parameter's own declaration or its schema. */\nexport interface ExampleSource {\n  example: unknown;\n  examples: unknown[] | undefined;\n}\n\n/**\n * Resolve `example` and `examples` across ordered precedence levels: for a\n * parameter its own declaration, its inline schema, then the component its\n * `$ref` points at; for a field its own schema, then its `$ref` target.\n *\n * Each value walks the levels independently. `examples` is the first\n * non-empty list. `example` comes from the first level that has either an\n * `example` or a list, preferring that level's own `example` over its first\n * list entry — so a schema-level `example` can never mask the parameter's\n * own `examples` map. A level with neither falls through; an explicit\n * `null` is a value and stops the walk.\n */\nexport function resolveExamples(levels: ExampleSource[]): ExampleSource {\n  let example: unknown;\n  let examples: unknown[] | undefined;\n  for (const level of levels) {\n    if (examples === undefined) examples = level.examples;\n    if (example === undefined) example = pickExample(level.example, level.examples);\n  }\n  return { example, examples };\n}\n\n/**\n * If a schema is a `$ref` to `#/components/schemas/X`, return the referenced\n * component schema. Used to surface schema-level metadata (default, example,\n * examples, deprecated, description) that would otherwise be invisible at the\n * field or parameter level.\n *\n * Refs are not pre-resolved by the bundler (`dereference: false` in refs.ts),\n * so without this, a param like `schema: { $ref: '.../PaginationOrder' }`\n * silently loses the target's `default: desc` and the SDK stops emitting the\n * spec-mandated default value in generated method signatures.\n */\nexport function resolveComponentSchemaRef(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): SchemaObject | undefined {\n  if (!schema || !componentSchemas) return undefined;\n  const ref = (schema as { $ref?: string }).$ref;\n  if (!ref) return undefined;\n  const match = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n  if (!match) return undefined;\n  return componentSchemas[match[1]];\n}\n\nexport interface ExtractedSchemas {\n  models: Model[];\n  enums: Enum[];\n}\n\nexport function extractSchemas(\n  schemas: Record<string, SchemaObject> | undefined,\n  options?: SchemaExtractionOptions,\n): ExtractedSchemas {\n  const enums: Enum[] = [];\n\n  if (!schemas) {\n    // No components, so no name transform is activated for this document;\n    // the titles are resolved here as they will be when the operations are\n    // typed, without one.\n    markContestedTitles(options?.document);\n    return { models: [], enums };\n  }\n\n  // Record the raw component keys first so every resolveSchemaName() call\n  // below (including the collision probe) can tell a real component key from\n  // a name oagen synthesised.\n  activeComponentSchemaKeys = new Set(Object.keys(schemas));\n  activeComponentSchemas = schemas;\n  // A new document: the references an `allOf` merge inherits from a\n  // component's property (`inheritedModelRefsOf`) are recorded per document,\n  // and so are the unions whose uncarried `properties` were reported.\n  resetInheritedModelRefs();\n  resetFoldWarnings();\n\n  // Build collision-safe transform if provided. The transform is probed with\n  // the same (cleaned, raw) pair resolveSchemaName() will hand it, so a\n  // transform that keys off the original spelling is collision-checked on the\n  // names it will actually produce. Collisions are tracked by raw key: two raw\n  // keys may clean to the same name yet transform to different ones (e.g.\n  // `Users`/`User` with an originalName-based transform), and marking the\n  // shared cleaned name unsafe would wrongly disable the transform for both.\n  if (options?.schemaNameTransform) {\n    const transform = options.schemaNameTransform;\n    const transformedToRawKeys = new Map<string, string[]>();\n    for (const raw of Object.keys(schemas)) {\n      const transformed = transform(cleanSchemaName(toPascalCase(raw)), raw);\n      if (!transformedToRawKeys.has(transformed)) transformedToRawKeys.set(transformed, []);\n      transformedToRawKeys.get(transformed)!.push(raw);\n    }\n    // Raw keys whose transformed output is shared with another raw key, plus\n    // their cleaned names. Component keys are guarded by raw key; synthesised\n    // names (no originalName) keep the cleaned-name guard they always had.\n    const unsafeRawKeys = new Set<string>();\n    const unsafeCleanedNames = new Set<string>();\n    for (const [, rawKeys] of transformedToRawKeys) {\n      if (rawKeys.length > 1) {\n        for (const raw of rawKeys) {\n          unsafeRawKeys.add(raw);\n          unsafeCleanedNames.add(cleanSchemaName(toPascalCase(raw)));\n        }\n      }\n    }\n    activeSchemaNameTransform = (name: string, originalName?: string) => {\n      const unsafe = originalName !== undefined ? unsafeRawKeys.has(originalName) : unsafeCleanedNames.has(name);\n      return unsafe ? name : transform(name, originalName);\n    };\n  } else {\n    activeSchemaNameTransform = null;\n  }\n\n  // Before any field is typed: which title-mapped variants must not keep\n  // their title because another shape takes it under the same root. Decided\n  // with the name transform active, since the titles are compared by the\n  // names they resolve to. The component schemas are read as one root; every\n  // other inline schema of the document is a root of its own.\n  markContestedTitles(options?.document ?? { components: { schemas } });\n\n  // Pre-compute the set of resolved names whose component schema is an enum so\n  // schemaToTypeRef() can classify `$ref` targets correctly. Built in a separate\n  // pass because the per-schema loop mutates models/enums and we want this map\n  // available before any TypeRef is resolved (operations + nested fields both\n  // call schemaToTypeRef during extraction).\n  activeEnumSchemaNames = new Set();\n  activeNullableEnumSchemaNames = new Set();\n  activeNullableUnionSchemaNames = new Set();\n  activeNamedUnionMemo = { plans: new WeakMap(), shapes: new WeakMap(), variantEntries: new WeakMap() };\n  for (const [name, schema] of Object.entries(schemas)) {\n    const resolved = resolveSchemaName(name);\n    if (isEnumComponentSchema(schema)) {\n      activeEnumSchemaNames.add(resolved);\n      if (isNullableEnumSchema(schema)) activeNullableEnumSchemaNames.add(resolved);\n    } else if (isNamedUnionSchema(schema) && isNullableUnionSchema(schema)) {\n      activeNullableUnionSchemaNames.add(resolved);\n    }\n  }\n\n  // The array components, planned once the sets above are complete, in\n  // rounds until the plans settle. Every tree starts under `item`. A round\n  // registers every tree under its current context — so a `$ref` to an\n  // array component resolves to its array in every rehearsal, the typing the\n  // real pass uses, which tells `{ value: { $ref: Notes } }` from `{ value:\n  // { $ref: Note } }` as `array<Note>` and `Note` — reads every name every\n  // other entry takes (`componentMints`) and every tree's names under its\n  // context (`arrayComponentMints`; the names a tree mints are read with\n  // none registered, so another component's items are never counted as its\n  // own), then decides the trees one at a time in the order of their keys\n  // sorted by code point — never the document's — each against every\n  // component and every other tree's current names (`planArrayComponent`),\n  // re-registering a tree that moves so the trees after it resolve its\n  // items under its new name. A round that moves nothing is the last: every\n  // shape was then compared under the names the plans settle on, so a tree\n  // whose items reference another tree is never shared on a provisional\n  // name (`array<PaletteItem>`) that the other tree then steps away from\n  // (`array<PaletteItemItem>`), and no two trees end on one name for\n  // different shapes, whatever the document's order. A `$ref` to an array\n  // component — from a component field, a named union's variant, an\n  // operation or a webhook — is then typed from its plan, by the key it\n  // names.\n  activeArrayComponentPlans = new Map();\n  const arrayComponents = Object.entries(schemas)\n    .filter(([, schema]) => !isEnumComponentSchema(schema) && isArrayComponentEntry(schema, schemas))\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n  if (arrayComponents.length > 0) {\n    const contexts = new Map(arrayComponents.map(([key]) => [key, 'item']));\n    const register = (): void => {\n      activeArrayComponentPlans = new Map(\n        arrayComponents.map(([key, schema]) => [key, arrayComponentPlan(key, schema, contexts.get(key)!)] as const),\n      );\n    };\n    let settled = false;\n    for (let round = 0; round < MAX_ARRAY_COMPONENT_ROUNDS && !settled; round++) {\n      register();\n      const minted = new Map(\n        Object.entries(schemas).map(([key, schema]) => [key, componentMints(key, schema, schemas)] as const),\n      );\n      const current = new Map(\n        arrayComponents.map(\n          ([key, schema]) =>\n            [key, arrayComponentMints(resolveSchemaName(key), schema, schemas, contexts.get(key)!)] as const,\n        ),\n      );\n      settled = true;\n      for (const [key, schema] of arrayComponents) {\n        const name = resolveSchemaName(key);\n        const own =\n          contexts.get(key) === 'item' ? current.get(key)! : arrayComponentMints(name, schema, schemas, 'item');\n        const others = new Map(current);\n        others.delete(key);\n        const context = planArrayComponent(name, schema, schemas, own, others, minted);\n        if (context === contexts.get(key)) continue;\n        settled = false;\n        contexts.set(key, context);\n        activeArrayComponentPlans.set(key, arrayComponentPlan(key, schema, context));\n        current.set(key, arrayComponentMints(name, schema, schemas, context));\n      }\n    }\n    if (!settled) {\n      console.warn(\n        `[oagen] Warning: The item names of the array components did not settle in ${MAX_ARRAY_COMPONENT_ROUNDS} rounds — keeping the last decision`,\n      );\n    }\n    register();\n  }\n\n  const modelsByCleanName = new Map<string, Model>();\n  // Keep the model with more fields when names collide after cleaning\n  // (two raw keys cleaning to one name), or when two inline models — a\n  // discriminated-allOf variant's, a named union's, an array component's\n  // items' — take one name.\n  const keepLarger = (model: Model): void => {\n    const existing = modelsByCleanName.get(model.name);\n    if (!existing || model.fields.length > existing.fields.length) modelsByCleanName.set(model.name, model);\n  };\n  // The key whose own model holds each name, so two keys that resolve to\n  // one name are told apart from a component and a variant of its own. Two\n  // such keys are one model only when their shapes agree\n  // (`modelFingerprint`: fields, types, limits); equal field counts say\n  // nothing, so a definition that differs is reported before it is dropped,\n  // as `keepLargestByName` reports one.\n  const componentKeysByName = new Map<string, string>();\n  const keepComponent = (key: string, model: Model): void => {\n    const other = componentKeysByName.get(model.name);\n    const existing = modelsByCleanName.get(model.name);\n    if (other !== undefined && existing && modelFingerprint(existing) !== modelFingerprint(model)) {\n      const kept =\n        model.fields.length > existing.fields.length\n          ? 'keeping the one with more fields'\n          : 'keeping the first definition';\n      console.warn(\n        `[oagen] Warning: Component schemas \"${other}\" and \"${key}\" both resolve to \"${model.name}\" with different fields or field types (${existing.fields.length} vs ${model.fields.length}) — ${kept}`,\n      );\n    }\n    if (other === undefined) componentKeysByName.set(model.name, key);\n    keepLarger(model);\n  };\n\n  for (const [name, schema] of Object.entries(schemas)) {\n    const pascalName = resolveSchemaName(name);\n\n    if (isEnumComponentSchema(schema)) {\n      enums.push(extractEnum(pascalName, schema));\n    } else if (activeArrayComponentPlans.has(name)) {\n      // No model of its own: a `$ref` to it is the array (`arrayComponentTypeRef`).\n      for (const inlineModel of extractArrayComponentModels(name, schemas)) keepLarger(inlineModel);\n    } else {\n      keepComponent(name, extractModel(pascalName, schema, schemas));\n\n      for (const inlineModel of [\n        ...extractDiscriminatedAllOfVariantModels(schema, pascalName, schemas),\n        ...extractNamedUnionVariantModels(schema, pascalName, schemas),\n      ]) {\n        keepLarger(inlineModel);\n      }\n    }\n  }\n\n  const models = [...modelsByCleanName.values()];\n\n  // Collect inline models from nested object/oneOf properties\n  // that schemaToTypeRef created model refs for but weren't extracted\n  const modelNames = new Set(models.map((m) => m.name));\n  const inlineQueue: Model[] = [...models];\n  while (inlineQueue.length > 0) {\n    const model = inlineQueue.pop()!;\n    for (const field of model.fields) {\n      collectNestedInlineModels(field.type, field.name, model.name, schemas ?? {}, models, modelNames, inlineQueue);\n    }\n  }\n\n  // Collect inline enums from model fields and named-union variants. One\n  // whose name a model extracted here owns (`Pet.kind` beside a `PetKind`\n  // object) is left on its ref: `collectInlineEnumsFromModels` promotes it\n  // under a distinct name once every model is known, as it does any clash.\n  for (const model of models) {\n    collectInlineEnums(model, enums, modelNames);\n  }\n  // ...and from every array component's items, which no model holds: the\n  // reference side types them, so an array of an inline enum lifts its enum\n  // whether or not anything refers to the component, as a named union's\n  // variant enum lifts through `variants`.\n  for (const name of activeArrayComponentPlans.keys()) {\n    const ref = arrayComponentTypeRef(name);\n    if (ref) collectInlineEnumFromRef(ref, enums, new Set(enums.map((e) => e.name)));\n  }\n\n  // NOTE: activeSchemaNameTransform is intentionally NOT cleared here.\n  // extractOperations() calls schemaToTypeRef() for $ref resolution and\n  // needs the same transform active. parseSpec() calls clearSchemaNameTransform()\n  // after all extraction is complete.\n  activeNamedUnionMemo = null;\n  return { models, enums };\n}\n\n/** Clear the module-level schemaNameTransform. Called by parseSpec() after all extraction phases. */\nexport function clearSchemaNameTransform(): void {\n  activeSchemaNameTransform = null;\n  activeEnumSchemaNames = new Set();\n  activeNullableEnumSchemaNames = new Set();\n  activeNullableUnionSchemaNames = new Set();\n  activeComponentSchemaKeys = new Set();\n  activeComponentSchemas = undefined;\n  activeNamedUnionMemo = null;\n  activeArrayComponentPlans = new Map();\n  markContestedTitles(undefined);\n}\n\n/**\n * Walk a single TypeRef and extract inline enum refs as top-level enum definitions.\n * Shared by both schemas.ts (field-level) and parse.ts (model-level) collection passes.\n *\n * The lifted `Enum` carries the `description` and link its schema declared\n * and each value's own `description` and `deprecated` (recorded against the\n * ref by `inlineEnumRef`), like a component enum. This is the one place an\n * inline enum becomes an `Enum`, whatever declared it — a property, a\n * parameter, a response header, a request, response, error or secondary\n * body, a webhook parameter or payload — so every site documents its enum\n * by one rule. The first ref lifted under a name decides the enum, its\n * `description`, link and value documentation included — the same\n * first-wins rule `seen` applies to the values — so a key is absent when\n * that schema declared no text or usable link, even if a later same-named\n * one does.\n */\nexport function collectInlineEnumFromRef(ref: TypeRef, enums: Enum[], seen: Set<string>): void {\n  walkTypeRef(ref, {\n    enum: (r) => {\n      if (r.values && !seen.has(r.name)) {\n        seen.add(r.name);\n        const description = inlineEnumDescriptionOf(r);\n        const externalDocs = inlineEnumExternalDocsOf(r);\n        const extensions = inlineEnumExtensionsOf(r);\n        enums.push({\n          name: r.name,\n          ...(description !== undefined ? { description } : {}),\n          values: enumValuesOf(r),\n          ...(externalDocs ? { externalDocs } : {}),\n          ...(extensions ? { extensions } : {}),\n        });\n      }\n    },\n  });\n}\n\n/**\n * Walk a model's type refs (its fields' types and, for a named union, its\n * variants) and extract inline enum refs as top-level enum definitions,\n * skipping one whose name is in `modelNames`: a model and an enum must never\n * share a name, and the collision-aware model pass\n * (`collectInlineEnumsFromModels`) renames and promotes that one later.\n * This ensures type alias files are generated for inline enums.\n */\nfunction collectInlineEnums(model: Model, enums: Enum[], modelNames: ReadonlySet<string>): void {\n  const seen = new Set(enums.map((e) => e.name));\n  for (const ref of collectModelTypeRefs(model)) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (!modelNames.has(r.name)) collectInlineEnumFromRef(r, enums, seen);\n      },\n    });\n  }\n}\n\n/**\n * Walk a TypeRef tree and extract inline models for any model refs that point\n * to schemas with inline object properties (not in components/schemas).\n * This handles nested objects like `totp: { oneOf: [{ type: object, properties: {...} }] }`\n * that schemaToTypeRef turns into model refs but aren't extracted from components.\n */\nfunction collectNestedInlineModels(\n  ref: TypeRef,\n  fieldName: string,\n  parentModelName: string,\n  schemas: Record<string, SchemaObject>,\n  models: Model[],\n  modelNames: Set<string>,\n  queue: Model[],\n): void {\n  // `extractNestedSchema` names what it extracts from the ref it is handed, so\n  // it is only right for refs the field schema produces directly — its own\n  // object, its array items, or its union variants. A ref deeper in the tree\n  // (the items of a variant's array member, a nested union) is named from its\n  // enclosing variant; handing it over here would re-derive the variants'\n  // names from it and register them under the wrong names. Those models come\n  // from the field extractor, which names them by construction.\n  const directRefs = directModelRefNames(ref);\n  walkTypeRef(ref, {\n    model: (modelRef) => {\n      if (modelNames.has(modelRef.name)) return; // already extracted\n      if (!directRefs.has(modelRef.name)) return; // nested under a variant — field extractor's\n      // Check if this model name corresponds to a component schema\n      // by checking all possible original names that would map to this PascalCase name\n      const isComponent = Object.keys(schemas).some((k) => resolveSchemaName(k) === modelRef.name);\n      if (isComponent) return; // will be extracted from components\n\n      // This is a reference to a nested inline model that wasn't extracted.\n      // Look up the field schema in the parent model's component schema to extract it.\n      const parentSchema = findSchemaByName(parentModelName, schemas);\n      if (!parentSchema) return;\n\n      // The declaration the field was typed from, never another member's.\n      const fieldSchema = componentFieldSchema(fieldName, parentModelName, parentSchema, schemas);\n      if (!fieldSchema) return;\n\n      // Extract inline models from the field schema. A union's variants are\n      // named from the field's own qualified name — `extractModel` and\n      // `extractAllOfModel` type every field of a component, inherited ones\n      // included, under the component — which is also variant 0's name\n      // unless variant 0 took its title (`CircleDrawingShape`). Rebuild the\n      // base from the field rather than reading it off the ref, and keep the\n      // ref as the base only if the rebuilt one does not reproduce it. The\n      // variants also step around the names the component's other properties\n      // mint, as the field's TypeRef did, so derive that set from the same\n      // sibling set `extractModel` typed the field with.\n      const reserved = reservedInlineNames(fieldName, collectProperties(parentSchema, schemas), parentModelName);\n      const baseName = unionBaseName(modelRef.name, fieldName, fieldSchema, parentModelName, reserved);\n      if (baseName === null) return; // a union's non-object variant — field extractor's\n      const extracted = extractNestedSchema(baseName, fieldSchema, schemas, reserved);\n      for (const m of extracted) {\n        if (!modelNames.has(m.name)) {\n          models.push(m);\n          modelNames.add(m.name);\n          queue.push(m); // re-scan for deeper nesting\n          // Remembered by the field it was read from, so the field's site\n          // can claim it by origin rather than by name when the field\n          // extractor's copy of the same schema is settled\n          // (`fieldInlineModelBundles`): `Foo.barThing` and `FooBar.thing`\n          // both spell `FooBarThing`, and only one of them is lifted.\n          recordLiftedFieldModel(parentModelName, fieldName, m);\n        }\n      }\n    },\n  });\n}\n\n/**\n * The base name `extractNestedSchema` should name a field's `oneOf` variants\n * from: `refName` itself (the ref the walk is resolving) for every non-union\n * field, and for a union field the field's qualified inline name when naming\n * the inline object variants from it yields `refName`. Null for a union\n * field whose inline object variants are not named `refName`: the ref was\n * minted for one of the union's other variants — a nullable wrapper around\n * an object, an `allOf`, a nested union — which `schemaToTypeRef` typed under\n * a context of its own (`nonObjectVariantContexts`) and which only the field\n * extractor materializes; naming the union's object variants from such a ref\n * would register variant 0's fields under the other variant's name.\n */\nfunction unionBaseName(\n  refName: string,\n  fieldName: string,\n  fieldSchema: SchemaObject,\n  parentModelName: string,\n  reserved: ReadonlySet<string>,\n): string | null {\n  if (!fieldSchema.oneOf) return refName;\n  const fromField = qualifyInlineModelName(toPascalCase(fieldName), parentModelName);\n  const names = [...nameInlineVariants(fieldSchema, fromField, reserved).values()];\n  return names.includes(refName) ? fromField : null;\n}\n\n/**\n * The model refs a field's TypeRef produces directly: the ref itself, the\n * items of a (possibly nullable) array, or each (possibly nullable) variant of\n * a union — the shapes `extractNestedSchema` can name from a ref. Refs nested\n * any deeper are excluded.\n */\nfunction directModelRefNames(ref: TypeRef): Set<string> {\n  const names = new Set<string>();\n  let root = ref;\n  while (root.kind === 'nullable' || root.kind === 'array') {\n    root = root.kind === 'nullable' ? root.inner : root.items;\n  }\n  const leaves = root.kind === 'union' ? root.variants : [root];\n  for (const leaf of leaves) {\n    const inner = leaf.kind === 'nullable' ? leaf.inner : leaf;\n    if (inner.kind === 'model') names.add(inner.name);\n  }\n  return names;\n}\n\n/** Find a component schema by PascalCase name. */\nfunction findSchemaByName(pascalName: string, schemas: Record<string, SchemaObject>): SchemaObject | null {\n  for (const [k, v] of Object.entries(schemas)) {\n    if (resolveSchemaName(k) === pascalName) return v;\n  }\n  return null;\n}\n\n/**\n * Every property a component schema's model has a field for, each with the\n * declarations it received (`PropertyDeclarations`), in field order: the one\n * answer to \"which schema declares `x` for this component\". The field\n * builders (`extractModel`, `extractAllOfModel`), the nested-model lookup\n * (`componentFieldSchema`, for `collectNestedInlineModels`) and the\n * component field pass (`extractInlineModelsFromSchemas`) all read it, so a\n * field and every model nested under it — an inline object, array items,\n * map values, a union's variants — are built from the same declaration. An\n * `allOf` component is read by `readComponentAllOf`; any other component\n * declares its own `properties` as always-applying and, with none, a pure\n * `oneOf`/`anyOf`'s variants' properties as branch-only — the flattening\n * `extractModel` gives such a union. `name` is the model's, for the\n * dispatcher detection a variant axis needs.\n */\nexport function componentPropertyLedger(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Map<string, PropertyDeclarations> {\n  const ledger = new Map<string, PropertyDeclarations>();\n  if (schema.allOf) {\n    readComponentAllOf(name, schema, schemas, ledger, new Set());\n    return ledger;\n  }\n  for (const [key, value] of Object.entries(schema.properties ?? {})) {\n    if (value) declareProperty(ledger, key, value, null, false);\n  }\n  if (ledger.size === 0) {\n    for (const variant of unionVariantsOf(schema) ?? []) {\n      for (const [key, value] of Object.entries(variant.properties ?? {})) {\n        if (value) declareProperty(ledger, key, value, null, true);\n      }\n    }\n  }\n  return ledger;\n}\n\n/**\n * The schema `fieldName` of the component `schema` (resolved to `name`) is\n * typed from — `declaredComponentProperty` over `componentPropertyLedger` —\n * or `null` when the component's model has no such field. The nested-model\n * pass builds a field's inline models from this very declaration, so a\n * model it builds (`OuterChild`) has the fields the field's type was built\n * from: a member's when one always declares the field, a branch's only when\n * no member does (workos/oagen#359 review: the lookup walked the schema and\n * returned the first declaration it met, a branch's before a later member's).\n */\nexport function componentFieldSchema(\n  fieldName: string,\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): SchemaObject | null {\n  const entry = componentPropertyLedger(name, schema, schemas).get(fieldName);\n  return entry ? declaredComponentProperty(entry) : null;\n}\n\n/**\n * Extract a model (and nested models) from an inline field schema. `reserved`\n * holds the inline names the field's sibling properties mint\n * (`reservedInlineNames`), which a `oneOf` variant must not take.\n */\nfunction extractNestedSchema(\n  name: string,\n  schema: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n): Model[] {\n  // Handle oneOf: extract each object variant as its own model. `name` is the\n  // union's base name (the field's qualified inline name), and the variants\n  // are named from it by `nameInlineVariants` — the one place that decides a\n  // variant's name — so they match the union TypeRef and the field extractor\n  // (`UserApiKeyOwner`, `CircleDrawingShape`, `DrawingShapeWithSide`, ...).\n  // Same inline-object test as `schemaToTypeRef` and the field extractor, so\n  // a `type: ['object', 'null']` variant is counted here too instead of\n  // letting the next variant claim its name.\n  //\n  // One keyword types the schema (`classifyInlineSchema`, the order\n  // `schemaToTypeRef` follows), so exactly one branch below runs: a schema\n  // carrying both `items` and `properties` is an array here as it is there,\n  // and never also an object model under the same name. `properties` beside\n  // the composition that types the schema are folded into it first, as\n  // `schemaToTypeRef` folds them, so the variants built here carry them.\n  schema = foldSiblingProperties(schema);\n  const kind = classifyInlineSchema(schema);\n  if (kind === 'union' && schema.oneOf) {\n    const models: Model[] = [];\n    const variantNames = nameInlineVariants(schema, name, reserved);\n    // A nullable wrapper (one non-null branch beside `null`) is the field's\n    // schema: the model built from its branch takes the wrapper's `deprecated`,\n    // limits and link (`collapsedNullableBranch`), exactly as the field\n    // extractor builds the same model, so the two copies agree. A multi-variant\n    // union, nullable or not, is not collapsed: every variant is built as\n    // written.\n    const branch = collapsedNullableBranch(schema);\n\n    for (const variant of schema.oneOf) {\n      const variantName = variantNames.get(variant);\n      if (variantName === undefined) continue;\n      const source = branch ?? variant;\n      // Build the variant's fields under its own name: an inline object\n      // nested under variant N is then referenced as `<VariantN>Child`\n      // (`ThingShapeWithSideCenter`), which is the name the field extractor\n      // materializes it under — not `<Variant0>Child`.\n      const requiredSet = new Set(source.required ?? []);\n      const siblings = collectProperties(source);\n      const fields: Field[] = [];\n      for (const [fn, fs] of Object.entries(source.properties ?? {})) {\n        if (!fs) continue;\n        fields.push(buildFieldFromSchema(fn, fs, variantName, requiredSet, schemas, siblings));\n      }\n      models.push({\n        name: variantName,\n        description: source.description,\n        ...externalDocsEntry(source.externalDocs),\n        fields,\n        ...deprecatedEntry(source),\n        ...constraintsEntry(source),\n        ...schemaExtensionsEntry(source),\n      });\n    }\n    return models;\n  }\n\n  // Handle direct object\n  if (kind === 'object' && schema.properties && (schema.type === 'object' || !schema.type)) {\n    const requiredSet = new Set(schema.required ?? []);\n    const siblings = collectProperties(schema);\n    const fields: Field[] = [];\n    for (const [fn, fs] of Object.entries(schema.properties)) {\n      if (!fs) continue;\n      fields.push(buildFieldFromSchema(fn, fs, name, requiredSet, schemas, siblings));\n    }\n    return [\n      {\n        name,\n        description: schema.description,\n        ...externalDocsEntry(schema.externalDocs),\n        fields,\n        ...deprecatedEntry(schema),\n        ...constraintsEntry(schema),\n        ...schemaExtensionsEntry(schema),\n      },\n    ];\n  }\n\n  // Handle array with inline items — typed, nullable, or `items` with no\n  // `type`: `isArraySchema` is `classifyInlineSchema`'s answer once the\n  // nullable type list is unwrapped, the same test `schemaToTypeRef` applied\n  // when it named the ref.\n  if (isArraySchema(schema) && schema.items?.properties) {\n    const requiredSet = new Set(schema.items.required ?? []);\n    const siblings = collectProperties(schema.items);\n    const fields: Field[] = [];\n    for (const [fn, fs] of Object.entries(schema.items.properties)) {\n      if (!fs) continue;\n      fields.push(buildFieldFromSchema(fn, fs, name, requiredSet, schemas, siblings));\n    }\n    return [\n      {\n        name,\n        description: schema.items.description,\n        ...externalDocsEntry(schema.items.externalDocs),\n        fields,\n        ...deprecatedEntry(schema.items),\n        ...constraintsEntry(schema.items),\n        ...schemaExtensionsEntry(schema.items),\n      },\n    ];\n  }\n\n  return [];\n}\n\n/**\n * The prefix a variant's `title` contributes to its name: the title trimmed\n * and PascalCased, or null when there is no title or it PascalCases to\n * nothing.\n */\nfunction variantTitlePrefix(variant: SchemaObject): string | null {\n  const title = typeof variant['title'] === 'string' ? variant['title'].trim() : '';\n  return title ? toPascalCase(title) || null : null;\n}\n\n/** `<Prefix><Base>`, or `base` unchanged when it already starts with the prefix (no doubling). */\nfunction prefixedVariantName(prefix: string, base: string): string {\n  return base.startsWith(prefix) ? base : `${prefix}${base}`;\n}\n\n/**\n * The properties `variant` declares that no other inline object variant of\n * the same union declares, in the variant's own `properties` order.\n */\nfunction distinguishingProperties(variant: SchemaObject, siblings: readonly SchemaObject[]): string[] {\n  const declaredElsewhere = new Set<string>();\n  for (const sibling of siblings) {\n    if (sibling === variant) continue;\n    for (const property of Object.keys(sibling.properties ?? {})) declaredElsewhere.add(property);\n  }\n  return Object.keys(variant.properties ?? {}).filter((property) => !declaredElsewhere.has(property));\n}\n\n/**\n * Name an inline object variant of a `oneOf`/`anyOf` that has no better\n * signal: it is not variant 0 (which keeps the union's base name) and no\n * const discriminator gave it a prefix. The name is derived from the\n * variant's own content, never from where it sits in the document (beyond\n * its position among the variants, which only the final counter reads), so\n * an SDK user can tell the variants apart and reordering them changes nothing\n * but which one is variant 0. In order, taking the first candidate that is\n * neither the base name nor a name already given to an earlier variant of\n * the same union:\n *\n *   1. the variant's `title` (trimmed and PascalCased): `<Title><Base>`\n *      (`CircleDrawingShape`), the same prefix form a const discriminator\n *      produces, including the rule that a base already starting with the\n *      prefix is not doubled (that candidate equals the base, so it falls\n *      through); a title an earlier variant already took falls through too;\n *   2. a distinguishing property — the first property, in the variant's own\n *      order, that it declares and no other inline object variant declares:\n *      `<Base>With<Property>` (`DrawingShapeWithSide`); a property that\n *      PascalCases to nothing is skipped;\n *   3. the position counter, `<Base><position + 1>` (`DrawingShape2`), which\n *      now remains only for variants whose property sets are identical, and\n *      which keeps counting past a taken name (`DrawingShape3`).\n *\n * Every candidate is also checked against `reserved`: the inline names the\n * parent's other properties mint (`reservedInlineNames`), so a variant can\n * never take a name another field's model already has — beside a\n * `shape_with_side` object, the `{ side }` variant of `shape` is not\n * `DrawingShapeWithSide` but the next candidate. Read from sibling names and\n * content only, so document order plays no part.\n *\n * `siblings` are the inline object variants of the union, this one included;\n * `emitted` are the names already given to the earlier ones, in order. Every\n * site that names a variant — the union TypeRef, the component-field,\n * request-body and response extractors, and `mintedInlineNames` — goes\n * through this function (via `nameInlineVariant`), so they cannot drift.\n */\nexport function nameUndiscriminatedVariant(\n  variant: SchemaObject,\n  siblings: readonly SchemaObject[],\n  base: string,\n  emitted: readonly string[],\n  reserved: ReadonlySet<string> = NO_RESERVED,\n): string {\n  const taken = (candidate: string): boolean =>\n    candidate === base || emitted.includes(candidate) || reserved.has(candidate);\n\n  const titlePrefix = variantTitlePrefix(variant);\n  if (titlePrefix !== null) {\n    const candidate = prefixedVariantName(titlePrefix, base);\n    if (!taken(candidate)) return candidate;\n  }\n\n  for (const property of distinguishingProperties(variant, siblings)) {\n    const word = toPascalCase(property);\n    if (!word) continue;\n    const candidate = `${base}With${word}`;\n    if (!taken(candidate)) return candidate;\n  }\n\n  for (let position = emitted.length + 1; ; position++) {\n    const candidate = `${base}${position}`;\n    if (!taken(candidate)) return candidate;\n  }\n}\n\n/** No reserved names: for a union with no sibling properties (a request body or response that is itself a union). */\nconst NO_RESERVED: ReadonlySet<string> = new Set();\n\n/**\n * True when the union's inline object variants (two or more) each carry a\n * title and no two titles PascalCase to the same prefix: the one case in\n * which variant 0 is named from its title rather than keeping the base name.\n */\nfunction allDistinctlyTitled(siblings: readonly SchemaObject[]): boolean {\n  if (siblings.length < 2) return false;\n  const prefixes = siblings.map(variantTitlePrefix);\n  return prefixes.every((prefix) => prefix !== null) && new Set(prefixes).size === prefixes.length;\n}\n\n/**\n * The name of one inline object variant of a `oneOf`/`anyOf`, given the\n * union's base name (the field's qualified inline name, e.g. `ApiKeyOwner`),\n * the inline object variants of the union (`siblings`, this one included),\n * the names already given to the earlier variants (`emitted`, in order), and\n * the const-valued property that distinguishes the variants when there is\n * one (`deriveConstNamingDiscriminator`).\n *\n * Variant 0 keeps the bare base name: the union TypeRef and every extractor\n * reference it under that name, and a consumer's typed field keeps the name\n * it always had. Two exceptions: when the union has no const discriminator\n * and every variant carries a distinct title, variant 0 is named from its\n * title like the others (`CircleDrawingShape` beside `SquareDrawingShape`)\n * instead of being the only one left bare; and when the caller says the base\n * is already taken (`baseTaken`: a component schema that is itself the\n * union, whose own model holds the base name — `Model.variants`), variant 0\n * is named like every later variant (`CatPet`, `PetWithLivesLeft`, `Pet1`).\n * Whether the union is discriminated is read from the variants themselves\n * here, not from `discriminator`, so a caller forcing a property (an explicit\n * `discriminator:` without `mapping:`) still agrees with the extractors on\n * variant 0.\n *\n * A later variant takes `<ConstValue><Base>` from the discriminator\n * (`UserApiKeyOwner`) when the value PascalCases to something and the name is\n * neither the base, nor already emitted, nor minted by one of the parent's\n * other properties (`reserved`), and otherwise falls to\n * `nameUndiscriminatedVariant`: its title, a distinguishing property, then\n * the position counter, each checked the same way.\n */\nexport function nameInlineVariant(\n  variant: SchemaObject,\n  siblings: readonly SchemaObject[],\n  base: string,\n  emitted: readonly string[],\n  discriminator: { property: string } | null,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n  baseTaken = false,\n): string {\n  if (emitted.length === 0 && !baseTaken) {\n    const undiscriminated = deriveConstNamingDiscriminator([...siblings]) === null;\n    const titlePrefix = undiscriminated && allDistinctlyTitled(siblings) ? variantTitlePrefix(variant) : null;\n    return titlePrefix === null ? base : prefixedVariantName(titlePrefix, base);\n  }\n\n  if (discriminator) {\n    const constValue = getConstPropertyValue(variant, discriminator.property);\n    const prefix = constValue ? toPascalCase(constValue) : '';\n    if (prefix) {\n      const candidate = prefixedVariantName(prefix, base);\n      if (candidate !== base && !emitted.includes(candidate) && !reserved.has(candidate)) return candidate;\n    }\n  }\n  return nameUndiscriminatedVariant(variant, siblings, base, emitted, reserved);\n}\n\n/**\n * Name every inline object variant of a `oneOf`/`anyOf` schema from the\n * union's base name, keyed by variant schema identity; null, non-object and\n * `$ref` variants get no entry. Positions are local to this variant list, so\n * the union's TypeRef entries and the extracted models agree no matter what\n * else has been extracted. `reserved` holds the inline names the parent's\n * other properties mint (`reservedInlineNames`); every site that has a\n * sibling set passes the same one, so the reference and the model step\n * around them identically.\n *\n * One union shape is named differently: a `oneOf` with no explicit\n * `discriminator:` whose every variant carries a `$ref` or a `title` and pins\n * the same const property (`titleMappedDiscriminatorProperty`). Its\n * discriminator mapping has always named an inline variant by its title\n * (`resolveSchemaName(title)`: `Circle`, `Square`, run through the project's\n * schema-name transform like a component), and `schemaToTypeRef` references\n * the variant by that mapped name, so the title is the model name here too —\n * unless it is the base, already emitted, or reserved by a sibling, in which\n * case the variant takes a context-qualified name (its title as a prefix on\n * the base, `CircleDrawingMarker`, else a distinguishing property, else the\n * counter) and the mapping, which is read from this map, follows it. A kept\n * title is context-free: it is the same whatever field, array or map the\n * union sits under, so it names one shape wherever it appears, as a\n * component name would. A second union beside it using the same title for a\n * variant of the identical shape (`schemaShapeKey`) therefore shares the\n * model instead of stepping around it; a sibling giving the same title a\n * different shape reserves it (`reservedInlineNames`), and since both sides\n * read their siblings in isolation the decision is symmetric: when the\n * shapes differ, both unions fall back to their context-qualified names\n * (`CircleDrawingShape`, `CircleDrawingMarker`) and neither keeps the bare\n * `Circle`; when they are identical, both keep `Circle` and one model is\n * emitted. The same holds at any depth of one root, not only between\n * siblings: a title that two unions anywhere under the same root — a\n * component schema, a request body, a response, a header, a webhook payload\n * — give different shapes is contested (`markContestedTitles`, decided\n * before any union is named), and a contested variant takes its\n * context-qualified name exactly as a reserved one does\n * (`CircleDrawingShape` beside `CircleDrawingMarkerShape`), wherever in the\n * root it sits and whichever is declared first. `elementContextName` never\n * lets a context-free name drive an items/values step-aside, which no\n * context could satisfy. `nameInlineVariantEntries` reports which names are\n * context-free; a fallen-back title name is context-dependent.\n *\n * This is the list-level entry point every site uses: `schemaToTypeRef` (via\n * `nameInlineObjectVariants`), `extractNestedSchema`,\n * `extractInlineModelDeep`, `extractInlineModelsFromProperties` and\n * `mintedInlineNames`.\n */\nexport function nameInlineVariants(\n  union: SchemaObject,\n  base: string,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n  baseTaken = false,\n): Map<SchemaObject, string> {\n  const names = new Map<SchemaObject, string>();\n  for (const [variant, entry] of nameInlineVariantEntries(union, base, reserved, baseTaken)) {\n    names.set(variant, entry.name);\n  }\n  return names;\n}\n\n/** A variant's model name, and whether it is context-free (a title-mapped union's title, see `nameInlineVariants`). */\nexport interface InlineVariantName {\n  name: string;\n  contextFree: boolean;\n}\n\n/**\n * `nameInlineVariants`, also telling for each name whether it is context-free.\n * `baseTaken` says the base name itself already belongs to another model (a\n * named union component's own), so variant 0 steps off it (`nameInlineVariant`).\n */\nexport function nameInlineVariantEntries(\n  union: SchemaObject,\n  base: string,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n  baseTaken = false,\n): Map<SchemaObject, InlineVariantName> {\n  const nonNullVariants = (union.oneOf ?? union.anyOf ?? []).filter((v) => !isNullVariantSchema(v));\n  const inlineObjectVariants = nonNullVariants.filter((v) => isInlineObjectSchema(v));\n  const discriminator = deriveConstNamingDiscriminator(inlineObjectVariants);\n  const titles = titleMappedVariantNames(union);\n  const emitted: string[] = [];\n  const entries = new Map<SchemaObject, InlineVariantName>();\n  for (const variant of inlineObjectVariants) {\n    let name: string | null = null;\n    let contextFree = false;\n    const titled = titles.get(variant);\n    if (titled !== undefined) {\n      if (titled !== base && !emitted.includes(titled) && !reserved.has(titled) && !isContestedTitle(variant)) {\n        name = titled;\n        contextFree = true;\n      } else {\n        // The title is taken (by a sibling's model, by a sibling's variant\n        // of a different shape, by an earlier variant of this union, or by a\n        // variant of another shape anywhere under the same root —\n        // `isContestedTitle`): the variant takes a context-qualified name\n        // instead — its title as a prefix on the base\n        // (`CircleDrawingMarker`), else a distinguishing property, else the\n        // counter — and the mapping, read from this map, follows.\n        name = nameUndiscriminatedVariant(variant, inlineObjectVariants, base, emitted, reserved);\n      }\n    }\n    name ??= nameInlineVariant(variant, inlineObjectVariants, base, emitted, discriminator, reserved, baseTaken);\n    emitted.push(name);\n    entries.set(variant, { name, contextFree });\n  }\n  return entries;\n}\n\n/**\n * The inline object variants of a title-mapped union — a `oneOf` with no\n * explicit `discriminator:` whose every non-null variant carries a `$ref` or\n * a `title` and pins the same const property\n * (`titleMappedDiscriminatorProperty`) — each with the name its title\n * resolves to (`resolveVariantModelName`: the title run through the\n * project's schema-name transform, like a component name). Empty for any\n * other union, so a caller can read \"is title-mapped\" off the map's size.\n * `nameInlineVariantEntries` names such a variant from this map, and\n * `markContestedTitles` reads the same map to find the variants that give\n * one title two shapes under one root, so the two cannot disagree on which\n * variants a title names.\n */\nexport function titleMappedVariantNames(union: SchemaObject): ReadonlyMap<SchemaObject, string> {\n  const names = new Map<SchemaObject, string>();\n  if (union.oneOf === undefined || union.discriminator) return names;\n  const nonNullVariants = union.oneOf.filter((v) => !isNullVariantSchema(v));\n  if (titleMappedDiscriminatorProperty(nonNullVariants) === null) return names;\n  for (const variant of nonNullVariants) {\n    if (!isInlineObjectSchema(variant)) continue;\n    const titled = resolveVariantModelName(variant);\n    if (titled !== null) names.set(variant, titled);\n  }\n  return names;\n}\n\n/**\n * Returns a discriminator descriptor when every inline object variant in a\n * oneOf has a string-const value on the same property — the signature of a\n * discriminated union without an explicit `discriminator:` keyword. Used by\n * `nameInlineVariant` to derive variant names from the const values.\n *\n * Distinct from `detectConstPropertyDiscriminator` (which requires every\n * variant to carry a `$ref` or `title` so a name mapping can be built):\n * this pass operates on inline anonymous variants, where naming is exactly\n * what we're trying to derive.\n */\nfunction deriveConstNamingDiscriminator(variants: SchemaObject[]): { property: string } | null {\n  if (variants.length < 2) return null;\n  const candidates = Object.keys(variants[0]?.properties ?? {});\n  for (const propName of candidates) {\n    const values = variants.map((v) => getConstPropertyValue(v, propName));\n    if (values.some((v) => v === null)) continue;\n    if (new Set(values).size !== values.length) continue; // collisions = no signal\n    return { property: propName };\n  }\n  return null;\n}\n\n/**\n * True for a schema that `schemaToTypeRef` turns into an inline model reference:\n * it declares `properties` directly (no `$ref`) and is an object — whether by\n * `type: 'object'`, by omitting `type`, or by an OAS 3.1 nullable array such as\n * `type: ['object', 'null']`. Every inline-model extractor must use the same\n * test, or a field's reference points at a model nobody materializes.\n */\nexport function isInlineObjectSchema(schema: SchemaObject | undefined): schema is SchemaObject {\n  if (!schema || schema.$ref || !schema.properties) return false;\n  const { type } = schema;\n  return type === undefined || type === 'object' || (Array.isArray(type) && type.includes('object'));\n}\n\n/** True when a named union admits `null`: a `type: 'null'` variant, a `type` list with `'null'`, or OAS 3.0 `nullable: true`. */\nfunction isNullableUnionSchema(schema: SchemaObject): boolean {\n  if (schema.nullable === true) return true;\n  if (Array.isArray(schema.type) && schema.type.includes('null')) return true;\n  return (schema.oneOf ?? schema.anyOf ?? []).some(isNullVariantSchema);\n}\n\n/**\n * True for a schema that `schemaToTypeRef` types as an array: `type: 'array'`,\n * an OAS 3.1 type list whose only non-null member is `array` (`['array',\n * 'null']`, which it unwraps to a nullable array), or — since JSON Schema does\n * not require `type` beside `items` — `items` with no `type` at all. Every\n * site that decides whether to materialize an array's item model must ask\n * this same question, or the items reference a model nobody creates. The\n * answer is `classifyInlineSchema`'s, asked of the schema with its nullable\n * type list unwrapped the way `schemaToTypeRef` unwraps it first: a `$ref` is\n * a reference whatever else it carries; a type list naming another type\n * beside `array` is a union; and a schema that also composes — a `oneOf` /\n * `anyOf` with a typing variant, or an `allOf` with a `$ref` member, a\n * member declaring properties inline or a lone typing member — is that composition,\n * `type: 'array'` or not, since it is read before `items` and the item\n * extractor must not claim a variant's name first. An `allOf` or `oneOf` of\n * bare limits (`[{ minItems: 1 }, { maxItems: 10 }]`) types nothing there and\n * leaves the schema an array here. `items` is not required: a bare\n * `type: 'array'` types nothing to `classifyInlineSchema` and is still an\n * array (of unknown items) to `schemaToTypeRef`; a site that needs items\n * checks for them. A plain boolean rather than a type guard, because a guard\n * on a `SchemaObject` narrows the variable to `never` in the other branch.\n */\nexport function isArraySchema(schema: SchemaObject | undefined): boolean {\n  if (!schema) return false;\n  let bare = schema;\n  if (Array.isArray(schema.type)) {\n    const nonNull = schema.type.filter((t) => t !== 'null');\n    if (nonNull.length !== 1) return false;\n    bare = { ...schema, type: nonNull[0] };\n  }\n  const kind = classifyInlineSchema(bare);\n  return kind === 'array' || (kind === 'other' && bare.type === 'array');\n}\n\n/**\n * The context each variant of a `oneOf`/`anyOf` that is not an inline object\n * is typed and extracted under, keyed by the variant. An inline object\n * variant is named by `nameInlineVariants` (`objectVariantNames`) and is not\n * in the map; a `null` variant marks the union nullable and a `$ref` variant\n * mints nothing, so neither is either. Every other variant is read with its\n * nullable wrapper removed, whichever form it takes (`unwrapNullableSchema`),\n * as the extractor reads it, and gets a context by its kind:\n *\n *   - an array or map variant is typed under `<field>_item` / `<field>_value`,\n *     so what its items or values mint (`ReqShapesItem`, `ReqShapesValue`)\n *     can never take the name an object variant of the same union keeps\n *     (`ReqShape`, `ReqShapeWithX`);\n *   - a variant that would mint a model or enum name under the field's own\n *     context — a nested `oneOf`/`anyOf` with inline object variants (its\n *     variants are named from the field's name as the outer ones are, so its\n *     first one would take the outer variant 0's name), a nullable wrapper\n *     around an inline object, an `allOf`, an inline enum or a union of\n *     string consts — keeps the field's context when nothing it mints there is\n *     claimed (a nested union beside a primitive still names its variants\n *     `ReqShape`, `BReqShape`; an inline enum beside a primitive keeps\n *     `ReqShape`), and is otherwise typed under `<field>_variant_<n>`, n its\n *     1-based position among the non-null variants, as a named union's\n *     non-object variants are (`memberContext`): the nested union's variants\n *     become `ReqShapeVariant2`, `BReqShapeVariant2`, an enum beside an object\n *     variant `ReqShapeVariant2`. Only context-dependent names take part in\n *     the claim check: a nested title-mapped union (`nameInlineVariants`:\n *     every variant titled and pinning the same const) mints its titles,\n *     `A` and `B`, under every context alike, so it keeps the field's\n *     context — it is in the map, so the extractor builds `A` and `B` — and\n *     steps only for a variant of its own that fell back to a\n *     context-qualified name (`AReqShape` when `A` is already taken);\n *   - a variant that mints nothing under the field's context (a primitive, an\n *     `allOf` of `$ref`s alone) keeps the field's context and is not in the map.\n *\n * A name is claimed when a sibling property mints it (a real `shapes_item`\n * object), the caller reserved it (`reservedNames`: the set an enclosing\n * field handed down to its array items or map values, or the names a\n * deferred body's registry already gives another shape — the same set the\n * object variants step around through `reservedNamesFor`), an inline object\n * variant of the union takes it (`ReqShape` — the reason a nested union's\n * variants step), an object variant's own property mints it (`item` under\n * `ReqShape` is `ReqShapeItem`), or an earlier variant of this map minted it.\n * When the context chosen by kind still mints a claimed name, it steps on\n * exactly as a plain array's items do beside such a sibling\n * (`firstFreeElementContext`: `shapes_array_item`, `shapes_array_item2`, …\n * for an array; `shapes_variant_2_value`, `shapes_variant_2_member_value`, …\n * for the rest), so no two variants of one union share a model, and neither\n * do a variant's items and an object variant's child. The names minted this\n * way are what `mintedInlineNameEntries` reports for the union, so a sibling\n * steps around them in turn. Decided in variant order, from the siblings' and\n * the variants' content only, so both sides of the parser agree:\n * `schemaToTypeRef` types each variant under its context, the extractors\n * re-enter with the variant as a property of that name, and\n * `mintedInlineNameEntries` reads the names under it.\n *\n * Each entry also carries the names the variant must step around when it is\n * typed and extracted under its context (`reserved`): everything claimed at\n * that point — the sibling-minted and caller-reserved names, the object\n * variants and their children, every name an earlier variant minted — plus\n * the context-free title an earlier variant kept for a different shape. Both\n * sides hand that set down as `reservedNames`, the set the enclosing field's\n * own variants step around through `reservedNamesFor`, so a nested\n * title-mapped variant whose title is already a sibling's model (`HolderA`\n * beside the `a` object of `Holder`), an earlier variant's model\n * (`HolderShapeVariant2`) or an earlier nested variant's title of another\n * shape falls back to its context-qualified name (`HolderAHolderShape`,\n * `AHolderShape`) exactly as a field-level titled variant does beside the\n * same sibling (`nameInlineVariantEntries`); an earlier nested variant's\n * title of the identical shape is shared, as between sibling fields\n * (`reservedInlineNames`). Without the set, the nested variant would keep\n * the title and the extractor would skip it as already built, so the union\n * would expose the sibling's fields. The names a variant mints are read with\n * its own set (`mintedInlineNameEntries`), so the claims a later variant\n * sees are the names actually taken.\n *\n * `objectVariantNames` is the name each inline object variant's model takes\n * (`nameInlineVariants`), as the caller decided it; those names, and the\n * names the models' own properties mint, are claimed before any context is\n * chosen. One level is enough: every name a child's children mint starts\n * with the child's.\n */\nexport function nonObjectVariantContexts(\n  contextName: string | undefined,\n  variants: readonly SchemaObject[],\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  objectVariantNames: ReadonlyMap<SchemaObject, string>,\n  reservedNames?: ReadonlySet<string>,\n): Map<SchemaObject, VariantContext> {\n  const contexts = new Map<SchemaObject, VariantContext>();\n  if (contextName === undefined) return contexts;\n  const claimed = new Set<string>(reservedNames);\n  for (const [siblingName, siblingSchema] of siblings ?? []) {\n    if (siblingName === contextName) continue;\n    for (const minted of mintedInlineNames(siblingName, siblingSchema, parentModelName)) claimed.add(minted);\n  }\n  for (const [variant, variantName] of objectVariantNames) {\n    claimed.add(variantName);\n    for (const [property, propertySchema] of Object.entries(unwrapNullableSchema(variant).properties ?? {})) {\n      if (!propertySchema) continue;\n      for (const minted of mintedInlineNames(property, propertySchema, variantName)) claimed.add(minted);\n    }\n  }\n  // The context-free title each earlier variant kept, with the shape it\n  // gave it: reserved for a later variant unless that variant gives the same\n  // title the identical shape, which then shares the model.\n  const keptTitles = new Map<string, string>();\n  let position = 0;\n  for (const variant of variants) {\n    if (isNullVariantSchema(variant)) continue;\n    position++;\n    if (objectVariantNames.has(variant)) continue;\n    const member = unwrapNullableSchema(variant);\n    const kind = classifyInlineSchema(member);\n    if (kind === 'ref') continue;\n    const ownTitles = new Map<string, string>();\n    for (const entry of mintedInlineNameEntries(contextName, member, parentModelName)) {\n      if (entry.contextFree && entry.schema) ownTitles.set(entry.name, schemaShapeKey(entry.schema));\n    }\n    const reserved = new Set(claimed);\n    for (const [title, shape] of keptTitles) if (ownTitles.get(title) !== shape) reserved.add(title);\n    const minted = (candidate: string): MintedInlineName[] =>\n      mintedInlineNameEntries(candidate, member, parentModelName, reserved);\n    const dependentNames = (candidate: string): string[] =>\n      minted(candidate)\n        .filter((entry) => !entry.contextFree)\n        .map((entry) => entry.name);\n    const unclaimed = (names: readonly string[]): boolean => names.every((name) => !reserved.has(name));\n    let context: string;\n    if (kind === 'array' || kind === 'map') {\n      context = firstFreeElementContext(\n        contextName,\n        kind === 'array' ? 'item' : 'value',\n        reserved,\n        dependentNames,\n        [],\n      ).context;\n    } else {\n      // A variant that mints nothing (a primitive, an `allOf` of `$ref`s\n      // alone) needs no entry. One that mints only context-free names — a\n      // nested title-mapped union, whose variants are `A` and `B` under\n      // every context — needs one, so the extractor builds those models, but\n      // never a step: no context could move such a name; a taken title is\n      // stepped off through `reserved` instead.\n      if (minted(contextName).length === 0) continue;\n      const own = dependentNames(contextName);\n      const stepped = `${contextName}_variant_${position}`;\n      const under = dependentNames(stepped);\n      context = unclaimed(own)\n        ? contextName\n        : unclaimed(under)\n          ? stepped\n          : firstFreeElementContext(stepped, 'value', reserved, dependentNames, under).context;\n    }\n    contexts.set(variant, { context, reserved });\n    for (const entry of minted(context)) {\n      if (entry.contextFree && entry.schema) keptTitles.set(entry.name, schemaShapeKey(entry.schema));\n      else claimed.add(entry.name);\n    }\n  }\n  return contexts;\n}\n\n/** How a non-object variant is typed and extracted: under `context`, stepping around `reserved` (see `nonObjectVariantContexts`). */\nexport interface VariantContext {\n  context: string;\n  reserved: ReadonlySet<string>;\n}\n\n/** Which of its keywords types an inline schema; see `classifyInlineSchema`. */\nexport type InlineSchemaKind = 'ref' | 'allOf' | 'union' | 'const' | 'enum' | 'array' | 'object' | 'map' | 'other';\n\n/**\n * Decide which of a schema's keywords types it when several could, in the\n * one precedence every site follows: `$ref`; then `allOf`; then `oneOf` /\n * `anyOf`; then `const`; then `enum`; then `items` as an array (with\n * `type: 'array'` or no `type`); then `properties` as an object (with\n * `type: 'object'`, no `type`, or a type list naming `object`); then a\n * property-less `type: 'object'` as a map. Anything else — a primitive, a\n * type list without `object`, an empty schema — is `other`.\n *\n * `schemaToTypeRef` and every inline-model extractor\n * (`extractInlineModelsFromProperties`, `mintedInlineNameEntries`, and\n * through them the response header and secondary-body paths) dispatch on\n * this, so a schema carrying both `items` and `oneOf` is a union to all of\n * them and the models extracted are exactly the ones the type references.\n * Call it on a schema whose nullable wrappers are already removed.\n */\nexport function classifyInlineSchema(schema: SchemaObject): InlineSchemaKind {\n  if (schema.$ref) return 'ref';\n  if (schema.allOf && allOfTypesSchema(schema.allOf)) return 'allOf';\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (variants && unionTypesSchema(variants)) return 'union';\n  if (schema.const !== undefined) return 'const';\n  if (schema.enum) return 'enum';\n  if (schema.items && (schema.type === 'array' || !schema.type)) return 'array';\n  // A plain boolean: the type guard would otherwise narrow `schema` to `never` below.\n  const inlineObject: boolean = isInlineObjectSchema(schema);\n  if (inlineObject) return 'object';\n  if (schema.type === 'object') return 'map';\n  return 'other';\n}\n\n/** Keywords that give a schema a type of its own; a member carrying none of them only adds limits or documentation. */\nconst TYPING_KEYWORDS: readonly string[] = [\n  '$ref',\n  'allOf',\n  'oneOf',\n  'anyOf',\n  'const',\n  'enum',\n  'items',\n  'properties',\n  'type',\n  'additionalProperties',\n  'patternProperties',\n];\n\n/**\n * Whether an `allOf` is what types the schema, i.e. the cases its branch in\n * `schemaToTypeRef` acts on: a `$ref` member (a reference, or an augmentation\n * model), a member declaring properties inline (a merged model —\n * `declaresInlineProperties`: its own `properties`, or those of a nested\n * `allOf` member or of a `oneOf`/`anyOf` variant, which `mergeAllOfMembers`\n * reads into the model), or a lone member that types on its own\n * (unwrapped). An `allOf` whose members only conjoin limits or\n * documentation — `allOf: [{ minProperties: 1 }, { maxProperties: 3 }]`\n * beside the schema's own `properties` — does not: the schema is then typed\n * from its own keywords, and `extractConstraints` still conjoins the\n * members' limits onto the field and the model it builds.\n */\nfunction allOfTypesSchema(members: readonly SchemaObject[]): boolean {\n  if (members.some((member) => member.$ref !== undefined || declaresInlineProperties(member))) return true;\n  const only = members.length === 1 ? members[0] : undefined;\n  return only !== undefined && TYPING_KEYWORDS.some((key) => (only as Record<string, unknown>)[key] !== undefined);\n}\n\n/**\n * Whether a `oneOf`/`anyOf` is what types the schema: so when any variant\n * carries a typing keyword. A union of bare constraint sets —\n * `anyOf: [{ required: ['k'] }, { maxProperties: 1 }]` beside the schema's\n * own `properties` — does not, as such an `allOf` does not: the schema is typed from its own\n * keywords (the object, with its `k`), and the variants only limit it.\n */\nfunction unionTypesSchema(variants: readonly SchemaObject[]): boolean {\n  return variants.some((variant) =>\n    TYPING_KEYWORDS.some((key) => (variant as Record<string, unknown>)[key] !== undefined),\n  );\n}\n\n/** The `{ type: 'null' }` member that marks a `oneOf`/`anyOf` as nullable; never a variant to name. */\nfunction isNullVariantSchema(schema: SchemaObject): boolean {\n  return (\n    schema.type === 'null' || (Array.isArray(schema.type) && schema.type.length === 1 && schema.type[0] === 'null')\n  );\n}\n\n/**\n * The schema `schemaToTypeRef` and every extractor dispatch on when a schema\n * writes `properties` beside a composition that types it: the composition,\n * carrying the properties. JSON Schema applies every keyword of one schema\n * at once, so `{ properties: { id }, allOf: [{ $ref: Pet }] }` is a `Pet`\n * that also has `id`, and `{ properties: { id }, oneOf: [pet, note] }` is\n * one of `pet` or `note` with `id` in either case. The parser reads a\n * composition before `properties` (`classifyInlineSchema`), so left as\n * written the properties would be dropped — while the response and\n * request-body paths, which read `properties` first, would drop the\n * composition instead and type the same schema two ways.\n *\n * An `allOf` gains the schema's own `properties` and `required` as its first\n * member, so the merge the parser already makes of such an `allOf` — the\n * augmentation of a `$ref` member, a model merged from inline members, a\n * single member unwrapped — carries them, the schema's own first. Each inline\n * object variant of a `oneOf`/`anyOf` (`isInlineObjectSchema`: `properties`\n * with `type: 'object'`, no `type`, or a type list naming `object`, so a\n * nullable or multi-typed object variant included) gains them, the schema's\n * own first and its own declaration kept where the variant declares the same\n * property, so the union keeps every variant and each carries the shared\n * properties. Every other variant is typed as written: a `$ref` names a\n * component the parser never merges properties into (it may be an enum or a\n * union it could not augment); a primitive, an array or an enum is no object,\n * so `properties` constrains nothing in it; a nested composition or a\n * nullable union wrapper is left to its own variants. `schemaToTypeRef`\n * reports the variants that may be objects and did not take the properties\n * (`warnOnUncarriedProperties`).\n *\n * Applies only when the schema's `type` admits an object (`object`, a type\n * list naming it, or none), it declares at least one property of its own\n * (`hasFoldableProperties`: an empty `properties: {}` leaves the schema as\n * written, so `{ properties: {}, allOf: [map] }` stays the map and\n * `{ properties: {}, oneOf: [...] }` the union as before) and the\n * composition is what types the schema — an `allOf` or `oneOf` of bare\n * limits beside `properties` leaves the schema the object it is. A property\n * is matched by its own name only (`Object.hasOwn`), so a field named\n * `constructor` or `toString` is a field. Returns the schema itself when nothing folds, else a\n * copy with no `properties` or `required` of its own, every other keyword —\n * `description`, `nullable`, limits, `discriminator`, `additionalProperties`\n * — kept; so folding a folded schema changes nothing. A folded variant is a\n * copy of the document's, and `foldedVariantOrigin` gives the document's\n * back, so a decision recorded against it (a contested title,\n * `isContestedTitle`) reaches the copy. A component schema's own\n * `properties` beside its `allOf` are read the same way, as its first\n * member, by `componentAllOfMembers`.\n */\nexport function foldSiblingProperties(schema: SchemaObject): SchemaObject {\n  if (!hasFoldableProperties(schema)) return schema;\n  const kind = classifyInlineSchema(schema);\n  if (kind !== 'allOf' && kind !== 'union') return schema;\n  const { properties, required, ...rest } = schema;\n  const own: SchemaObject = { type: 'object', properties, ...(required && required.length > 0 && { required }) };\n  if (kind === 'allOf') return { ...rest, allOf: [own, ...(schema.allOf ?? [])] };\n  const conjoin = (variant: SchemaObject): SchemaObject => conjoinSiblingProperties(variant, own);\n  return schema.oneOf\n    ? { ...rest, oneOf: schema.oneOf.map(conjoin) }\n    : { ...rest, anyOf: (schema.anyOf ?? []).map(conjoin) };\n}\n\n/**\n * Whether `schema` declares at least one property of its own that a\n * composition beside them could carry (see `foldSiblingProperties`). An\n * empty `properties: {}` declares none: folded, it would add an empty object\n * member that types the schema as a model the extractor builds nothing for\n * (`{ properties: {}, allOf: [map] }` is the map, as written).\n */\nfunction hasFoldableProperties(schema: SchemaObject): boolean {\n  if (schema.$ref || schema.properties === undefined || Object.keys(schema.properties).length === 0) return false;\n  const { type } = schema;\n  return type === undefined || type === 'object' || (Array.isArray(type) && type.includes('object'));\n}\n\n/**\n * The members a component schema's `allOf` model is built from: the schema's\n * own `properties` and `required`, when it declares a property\n * (`hasFoldableProperties`), as one more member — the first — then the\n * members as written. JSON Schema applies both at once, so\n * `Dog: { allOf: [{ $ref: Pet }], properties: { breed }, required: [breed] }`\n * has `Pet`'s properties and `breed`: the own keywords are read here exactly\n * as `foldSiblingProperties` folds them for an inline schema, and as\n * `mergeAllOfMembers` reads this component when a `$ref` member names it\n * (its own properties, then its members), so the component's model and an\n * inline merge that names it carry its own and inherited properties in the\n * same order (workos/oagen#307: the component's own properties were not\n * read, and `Dog` was `{ name }`). Shared by `extractAllOfModel`, at every level of a\n * `$ref` chain, and by `extractDiscriminatedAllOfVariantModels`, whose\n * dispatcher base carries them into every variant. A `oneOf`/`anyOf`\n * beside a component's `properties` keeps its own rule — the object model\n * (`extractModel`) — and is not read here.\n */\nfunction componentAllOfMembers(schema: SchemaObject): readonly SchemaObject[] {\n  const members = schema.allOf ?? [];\n  if (!hasFoldableProperties(schema)) return members;\n  const { properties, required } = schema;\n  return [{ type: 'object', properties, ...(required && required.length > 0 && { required }) }, ...members];\n}\n\n/**\n * `variant` carrying `own`'s properties and required names when it is an\n * inline object (`isInlineObjectSchema`), itself otherwise. The schema's own\n * properties come first and win where both declare a name; the required\n * names are the union of both lists.\n */\nfunction conjoinSiblingProperties(variant: SchemaObject, own: SchemaObject): SchemaObject {\n  if (!isInlineObjectSchema(variant)) return variant;\n  const properties: Record<string, SchemaObject | undefined> = { ...own.properties };\n  for (const [name, property] of Object.entries(variant.properties ?? {})) {\n    if (!Object.hasOwn(properties, name)) properties[name] = property;\n  }\n  const required = [...new Set([...(own.required ?? []), ...(variant.required ?? [])])];\n  const folded: SchemaObject = { ...variant, properties, ...(required.length > 0 && { required }) };\n  foldedVariantOrigins.set(folded, foldedVariantOrigin(variant) ?? variant);\n  return folded;\n}\n\n/** The document's variant each folded copy was made from (`conjoinSiblingProperties`). */\nconst foldedVariantOrigins = new WeakMap<SchemaObject, SchemaObject>();\n\n/** The document's variant `variant` is a folded copy of, or `undefined` when it is the document's own. */\nexport function foldedVariantOrigin(variant: SchemaObject): SchemaObject | undefined {\n  return foldedVariantOrigins.get(variant);\n}\n\n/**\n * The `oneOf`/`anyOf` lists `warnOnUncarriedProperties` has reported, so a\n * union is reported once however many times it is typed. Keyed by the list,\n * which every nullable unwrap keeps while it copies the schema around it.\n * Replaced per document (`resetFoldWarnings`).\n */\nlet reportedUncarriedProperties = new WeakSet<readonly SchemaObject[]>();\n\n/** Forget which unions `warnOnUncarriedProperties` has reported; called once per document (`extractSchemas`). */\nexport function resetFoldWarnings(): void {\n  reportedUncarriedProperties = new WeakSet();\n}\n\n/**\n * Warn, once per union, when `properties` written beside a typing\n * `oneOf`/`anyOf` are not carried into a variant that may be an object — a\n * `$ref`, an `allOf`, a nested union, a map, or a nullable union wrapper\n * around an object — because only an inline object variant takes them\n * (`foldSiblingProperties`). A primitive, array or enum variant is no object\n * and is not reported. Called by `schemaToTypeRef` with the context it types\n * the schema under, before the fold, on the schema as written — and by the\n * response and request-body paths, which fold a body before anything types\n * it, on the body as written under the body's name.\n */\nexport function warnOnUncarriedProperties(\n  schema: SchemaObject,\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n): void {\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (!variants || !hasFoldableProperties(schema) || classifyInlineSchema(schema) !== 'union') return;\n  if (reportedUncarriedProperties.has(variants)) return;\n  const uncarried: number[] = [];\n  variants.forEach((variant, index) => {\n    if (isNullVariantSchema(variant) || isInlineObjectSchema(variant)) return;\n    const kind = classifyInlineSchema(unwrapNullableSchema(variant));\n    if (kind === 'ref' || kind === 'allOf' || kind === 'union' || kind === 'map' || kind === 'object') {\n      uncarried.push(index + 1);\n    }\n  });\n  if (uncarried.length === 0) return;\n  reportedUncarriedProperties.add(variants);\n  const keyword = schema.oneOf ? 'oneOf' : 'anyOf';\n  const which = uncarried.length === 1 ? `variant ${uncarried[0]} is` : `variants ${uncarried.join(', ')} are`;\n  const context =\n    contextName === undefined ? '' : ` (context: ${parentModelName ? `${parentModelName}.` : ''}${contextName})`;\n  console.warn(\n    `[oagen] Warning: \\`properties\\` beside \\`${keyword}\\` are carried into its inline object variants only; ${which} typed as written, without them${context}`,\n  );\n}\n\n/**\n * The synthetic context names a multi-type inline variant's non-object\n * members are typed and extracted under, chosen so the models they name can\n * never collide with a model named from one of the variant's own properties.\n * An `array` member's items go under `item` (`<Variant>Item`), falling back\n * to `array_item` (`<Variant>ArrayItem`) and then `array_item2`,\n * `array_item3`, ... when a property already claims that name; any other\n * member goes under `value` (`<Variant>Value`), then `member_value`,\n * `member_value2`, .... A candidate is skipped when the model name\n * `qualifyInlineModelName` derives from it equals one derived from a\n * property — compared after qualification, so a property `items`, whose\n * name singularizes to `<Variant>Item`, blocks `item` as well.\n * This is the single source of these names for the TypeRef builder\n * (`inlineVariantTypeRef`) and the extractors (`variantMemberSchemas`).\n */\nexport function variantMemberKeys(variant: SchemaObject, variantName: string): { item: string; value: string } {\n  const modelNameFor = (key: string): string => qualifyInlineModelName(toPascalCase(key), variantName);\n  const claimed = new Set(Object.keys(variant.properties ?? {}).map(modelNameFor));\n  const pick = (preferred: string, fallback: string): string => {\n    for (let i = 0; ; i++) {\n      const candidate = i === 0 ? preferred : i === 1 ? fallback : `${fallback}${i}`;\n      if (!claimed.has(modelNameFor(candidate))) return candidate;\n    }\n  };\n  return { item: pick('item', 'array_item'), value: pick('value', 'member_value') };\n}\n\n/**\n * The schemas carried by the non-object members of a multi-type inline\n * variant (`type: ['object', 'array']` with `items`), keyed by the synthetic\n * context name from `variantMemberKeys` that `schemaToTypeRef` types them\n * under, so an inline object item is `<Variant>Item` (or `<Variant>ArrayItem`\n * when `item` is taken) and its own nested objects `<Variant>ItemChild`.\n * Every extractor re-enters with these under the variant's name so the\n * models line up with the refs by construction. A map member cannot occur\n * here: a variant with `properties` is typed as a model, never as a map.\n */\nexport function variantMemberSchemas(variant: SchemaObject, variantName: string): Record<string, SchemaObject> {\n  const members: Record<string, SchemaObject> = {};\n  if (Array.isArray(variant.type) && variant.type.includes('array') && variant.items) {\n    members[variantMemberKeys(variant, variantName).item] = variant.items;\n  }\n  return members;\n}\n\n/**\n * Build a single Field from a schema property entry. Shared across all\n * extraction sites. Pass `componentSchemas` where they are at hand so a\n * field whose schema is a bare `$ref` can take `example`/`examples` from the\n * component it points at, as a parameter does. `siblingProperties` are the\n * other properties of the object the field belongs to (`collectProperties`);\n * array items and map values use them to step aside from a sibling that\n * would take their singular name (`elementContextName`).\n */\nexport function buildFieldFromSchema(\n  fieldName: string,\n  fieldSchema: SchemaObject,\n  contextName: string,\n  requiredSet: Set<string>,\n  componentSchemas?: Record<string, SchemaObject>,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n): Field {\n  const refTarget = resolveComponentSchemaRef(fieldSchema, componentSchemas);\n  const { example, examples } = resolveExamples([\n    { example: fieldSchema.example, examples: nonEmptyExamples(fieldSchema.examples) },\n    { example: refTarget?.example, examples: nonEmptyExamples(refTarget?.examples) },\n  ]);\n  // A bare `$ref` to an array component names no model that could carry the\n  // component's `description`, `deprecated` and `externalDocs`, so the field\n  // takes them when it declares none of its own, as it takes the component's\n  // `example`. A `$ref` to a model, named union or enum leaves them on it.\n  const alias = refTarget !== undefined && isArrayComponentRef(fieldSchema) ? refTarget : undefined;\n  const externalDocs = readExternalDocs(fieldSchema.externalDocs) ?? readExternalDocs(alias?.externalDocs);\n  const extensions =\n    extensionsOf(fieldSchema, SCHEMA_CONSUMED_EXTENSIONS) ??\n    (alias ? extensionsOf(alias, SCHEMA_CONSUMED_EXTENSIONS) : undefined);\n  return {\n    name: fieldName,\n    type: schemaToTypeRef(fieldSchema, fieldName, contextName, siblingProperties),\n    required: requiredSet.has(fieldName),\n    description: fieldSchema.description ?? alias?.description,\n    // The field schema's own link, read like `description`: a sibling of a\n    // `$ref` is the field's, and a bare `$ref` gives none — the referenced\n    // model carries its own — unless the `$ref` names an array component.\n    ...(externalDocs ? { externalDocs } : {}),\n    readOnly: fieldSchema.readOnly || undefined,\n    writeOnly: fieldSchema.writeOnly || undefined,\n    deprecated: fieldSchema.deprecated === true || alias?.deprecated === true || undefined,\n    default: fieldSchema.default,\n    example,\n    // Only materialise the key when there is something to carry so existing\n    // inline snapshots of fields without examples stay byte-identical.\n    ...(examples ? { examples } : {}),\n    // Keywords written beside a `$ref` (legal in OAS 3.1) are the field's own;\n    // a bare `$ref` declares none, and the referenced model carries its limits.\n    ...constraintsEntry(fieldSchema),\n    // The schema's own `x-*` keys, read the same way; a `$ref` to an array\n    // component that declares none takes the component's, as it takes its\n    // `description`.\n    ...(extensions ? { extensions } : {}),\n  };\n}\n\n/**\n * Build an EnumRef the same way the regular enum path does for naming. The\n * `oneOf`/`anyOf` wrapper is the schema that declares this enum, so its\n * `description` and link are the enum's (`rawDescription`,\n * `rawExternalDocs`), as an inline `enum:` schema's are; the members carry\n * each variant's own documentation (`constUnionEnumMembers`).\n */\nfunction buildSyntheticEnumRef(\n  members: readonly EnumMember[],\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n  rawExternalDocs: unknown,\n  rawDescription: unknown,\n  extensions: Extensions | undefined,\n): TypeRef {\n  return inlineEnumRef(\n    inlineEnumName(contextName, parentModelName),\n    members,\n    rawExternalDocs,\n    rawDescription,\n    extensions,\n  );\n}\n\n/**\n * The name `schemaToTypeRef` gives an inline enum typed under `contextName`\n * (`GetPetError404`; `status` → `Status`): qualified by `parentModelName`\n * with its list-item markers stripped (`DirectoryListItem` + `State` →\n * `DirectoryState`) unless the name already starts with it (`Connection` +\n * `ConnectionType` → `ConnectionType`), then passed through the active\n * `schemaNameTransform` as a component's name is, so a project's rename map\n * (`RadarAction` → `RadarListAction` in `oagen.config.ts`) reaches inline\n * enums too. One rule for every inline enum: an `enum:` list, a `oneOf` of\n * consts (`buildSyntheticEnumRef`), and the name a deferred body that is an\n * enum is reserved under before it is typed (`inlineEnumSchemaName`).\n */\nexport function inlineEnumName(contextName: string | undefined, parentModelName: string | undefined): string {\n  const baseName = toPascalCase(contextName ?? 'UnknownEnum');\n  const cleanParent = parentModelName ? stripListItemMarkers(parentModelName) : undefined;\n  const qualifiedName = cleanParent && !baseName.startsWith(cleanParent) ? `${cleanParent}${baseName}` : baseName;\n  return activeSchemaNameTransform ? activeSchemaNameTransform(qualifiedName) : qualifiedName;\n}\n\n/**\n * How `schemaToTypeRef` types a schema as an inline enum, when it does. The\n * one decision both the typer's enum branches and `inlineEnumSchemaName`\n * read, so the name a pass reserves before a schema is typed and the name\n * the schema is typed under can never disagree. Decided on the schema as\n * the typer sees it at those branches — its nullable wrappers removed, so\n * callers unwrap first (`unwrapNullableSchema`): a `oneOf`/`anyOf` whose\n * non-null variants are string `const` schemas (`constUnionEnumMembers`)\n * with two or more members, or any number beside an `enum:` list that\n * restricts them, is a `const-union` enum of those members; an `enum:` list\n * of any count of non-null members but one is an `enum-list` enum, one\n * alone being a literal; every other shape — a `$ref`, an `allOf`, a union\n * of other variants, an object, an array — is not an enum here (an array's\n * items are the array's question, `inlineEnumSchemaName`).\n */\nexport function inlineEnumSpelling(schema: SchemaObject): InlineEnumSpelling | undefined {\n  const kind = classifyInlineSchema(schema);\n  if (kind === 'union') {\n    const members = constUnionEnumMembers(schema);\n    if (members !== null && (members.length >= 2 || Array.isArray(schema.enum))) {\n      return { spelling: 'const-union', members };\n    }\n    return undefined;\n  }\n  if (kind === 'enum' && nonNullEnumValues(schema.enum).length !== 1) return { spelling: 'enum-list' };\n  return undefined;\n}\n\n/** The two spellings of an inline enum `schemaToTypeRef` lifts (`inlineEnumSpelling`), with the const union's members. */\nexport type InlineEnumSpelling = { spelling: 'const-union'; members: EnumMember[] } | { spelling: 'enum-list' };\n\n/**\n * The enum name `schemaToTypeRef` types `schema` under — a schema it types\n * as an inline enum in either spelling (`inlineEnumSpelling`), under any\n * nullable wrapper, or an array of one, which is lifted under the array's\n * own name — or undefined when it types the schema as something else. Lets\n * a pass reserve the enum's name before the schema is typed\n * (`extractOperations`), whatever the document order of the sites.\n */\nexport function inlineEnumSchemaName(\n  schema: SchemaObject,\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n): string | undefined {\n  const inner = unwrapNullableSchema(schema);\n  if (classifyInlineSchema(inner) === 'array') {\n    const items = inner.items;\n    return items && !Array.isArray(items) ? inlineEnumSchemaName(items, contextName, parentModelName) : undefined;\n  }\n  return inlineEnumSpelling(inner) ? inlineEnumName(contextName, parentModelName) : undefined;\n}\n\n/**\n * Detect an implicit discriminator on a `oneOf` whose every variant pins the\n * same property to a const value AND is nameable on its own — by a `$ref` to\n * a component or by a `title` — so the IR can represent the union as\n * discriminated, with a mapping to concrete names, without an explicit\n * `discriminator:` keyword. Returns the property, or null when any variant\n * doesn't fit the pattern or when the variants disagree on which property\n * carries the discriminator. The mapping itself is built by `schemaToTypeRef`\n * from the names `nameInlineVariants` gives the inline variants (their titles\n * unless taken) and the component names of `$ref` variants, so it can only\n * ever point at a model that exists.\n *\n * Both const shapes are supported:\n *   { properties: { event: { const: \"x\" } }, required: [\"event\"] }\n *   { properties: { event: { type: \"string\", enum: [\"x\"] } } }\n */\nfunction titleMappedDiscriminatorProperty(variants: SchemaObject[]): string | null {\n  if (variants.length < 2) return null;\n  // Require a $ref or title on every variant so there is a concrete name to map to.\n  if (!variants.every((v) => resolveVariantModelName(v) !== null)) return null;\n\n  // The first property whose const value is present on every variant.\n  const candidates = Object.keys(variants[0]?.properties ?? {});\n  for (const propName of candidates) {\n    if (variants.every((v) => getConstPropertyValue(v, propName) !== null)) return propName;\n  }\n  return null;\n}\n\nfunction getConstPropertyValue(schema: SchemaObject, property: string): string | null {\n  const prop = schema.properties?.[property];\n  if (!prop) return null;\n  if (typeof prop.const === 'string') return prop.const;\n  if (Array.isArray(prop.enum) && prop.enum.length === 1 && typeof prop.enum[0] === 'string') {\n    return prop.enum[0];\n  }\n  return null;\n}\n\nfunction resolveVariantModelName(schema: SchemaObject): string | null {\n  if (schema.$ref) {\n    return resolveSchemaName(schema.$ref.replace(/^#\\/components\\/schemas\\//, ''));\n  }\n  const title = typeof schema['title'] === 'string' ? (schema['title'] as string) : null;\n  if (title) return resolveSchemaName(title);\n  return null;\n}\n\n/** Look up the discriminator's mapped variant name for an inline object\n *  variant by reading its const-valued discriminator property. Returns null\n *  when the variant doesn't pin the property to a string const, or when\n *  the value isn't in the mapping. */\nfunction mapVariantToDiscriminatorEntry(\n  variant: SchemaObject,\n  discriminator: { property: string; mapping: Record<string, string> },\n): string | null {\n  const value = getConstPropertyValue(variant, discriminator.property);\n  if (value === null) return null;\n  // Own keys only: a const spelled like an inherited property (`constructor`)\n  // must not resolve to `Object.prototype`'s.\n  return Object.hasOwn(discriminator.mapping, value) ? (discriminator.mapping[value] ?? null) : null;\n}\n\n/**\n * Derive a discriminator value → variant model name mapping for an inline-\n * variant `oneOf` from the names `nameInlineVariants` gave its variants\n * (`inlineVariantNames`): the explicit `discriminator:` without a `mapping:`\n * clause, and the implicit const discriminator of anonymous inline variants\n * (`ApiKeyCreatedData.owner`: `ApiKeyCreatedDataOwner`,\n * `UserApiKeyCreatedDataOwner`). Reading the names rather than deriving them\n * again is what keeps the mapping pointing at models the extractors create.\n * Returns null without a context name, when any variant is not an inline\n * object, or when a variant lacks a const value on the property.\n */\nfunction deriveInlineVariantMapping(\n  variants: SchemaObject[],\n  discriminatorProperty: string,\n  contextName: string | undefined,\n  inlineVariantNames: ReadonlyMap<SchemaObject, string>,\n): Record<string, string> | null {\n  if (variants.length === 0 || !contextName) return null;\n  const mapping: Record<string, string> = {};\n  for (const variant of variants) {\n    const variantName = inlineVariantNames.get(variant);\n    if (variantName === undefined) return null;\n    const constValue = getConstPropertyValue(variant, discriminatorProperty);\n    if (constValue === null) return null;\n    mapping[constValue] = variantName;\n  }\n  return mapping;\n}\n\n/**\n * The names reserved for a union typed under `contextName`: the set an\n * enclosing field handed down (`reservedNames`, for a union among a field's\n * array items or map values), else the inline names the field's own sibling\n * properties mint (`reservedInlineNames`), else nothing. The extractor\n * derives the same set at each of those levels, so the reference and the\n * model step around a sibling's name identically.\n */\nfunction reservedNamesFor(\n  contextName: string | undefined,\n  siblingProperties: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  reservedNames: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n  if (reservedNames) return reservedNames;\n  if (contextName === undefined) return NO_RESERVED;\n  return reservedInlineNames(contextName, siblingProperties, parentModelName);\n}\n\n/**\n * Name the inline object variants of a field's `oneOf`/`anyOf` exactly as the\n * inline-model extractors do (`extractInlineModelsFromProperties` in\n * inline-models.ts, and `extractNestedSchema` / `extractInlineModelDeep`\n * here): the union's base name is the field's qualified inline name, the\n * names the field's sibling properties mint — or the set handed down from an\n * enclosing field — are reserved (`reservedNamesFor`), and\n * `nameInlineVariants` hands out the variant names from there. Returned keyed\n * by variant schema identity.\n */\nfunction nameInlineObjectVariants(\n  union: SchemaObject,\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n  siblingProperties: ReadonlyMap<string, SchemaObject> | undefined,\n  reservedNames: ReadonlySet<string> | undefined,\n): Map<SchemaObject, string> {\n  const baseInlineName = qualifyInlineModelName(toPascalCase(contextName ?? 'UnknownModel'), parentModelName);\n  return nameInlineVariants(\n    union,\n    baseInlineName,\n    reservedNamesFor(contextName, siblingProperties, parentModelName, reservedNames),\n  );\n}\n\n/**\n * The TypeRef for an inline object variant whose extracted model is\n * `modelName`, keeping every other type the variant allows. Mirrors what\n * `schemaToTypeRef` builds for the same schema — one member per non-null\n * entry of a `type` array, `union`-wrapped when there is more than one,\n * `nullable`-wrapped when `null` or OAS 3.0 `nullable: true` is present —\n * with the `object` member swapped for a ref to `refName`: the model's own\n * name, or the component the spec's `discriminator.mapping` points the\n * variant's const at, which substitutes for the model exactly as it does\n * inline (`mapVariantToDiscriminatorEntry`).\n * `type: ['object', 'string']` → `union[model, string]`,\n * `['object', 'integer', 'null']` → `nullable<union[model, integer]>`,\n * `['object', 'null']` / `nullable: true` → `nullable<model>`.\n * A `oneOf: [X, { type: 'null' }]` variant has no `properties` of its own\n * and never reaches this path; `schemaToTypeRef` types it directly.\n *\n * Anything inline under a non-object member is named from the variant's\n * model — never from the union's field, and never from the mapping: an\n * `array` member types its items under `modelName` as parent with the\n * context `variantMemberKeys` picks (`item` → `<Variant>Item`, or\n * `array_item` → `<Variant>ArrayItem` when a property claims `item`), and\n * any other member under its `value` key (`<Variant>Value` for an inline\n * enum, else `<Variant>MemberValue`). The extractor materializes those\n * members under the same model (`variantMemberSchemas`), which it builds\n * whether or not the mapping redirects the object member; naming them from\n * the mapped component would reference `CatItem`, which nothing extracts,\n * and naming them from the field would hand variant 0's model name to every\n * variant's items.\n */\nfunction inlineVariantTypeRef(variant: SchemaObject, modelName: string, refName: string = modelName): TypeRef {\n  const modelRef: TypeRef = { kind: 'model', name: refName };\n  const typeList = Array.isArray(variant.type) ? variant.type : [];\n  const nullable = variant.nullable === true || typeList.includes('null');\n  const keys = variantMemberKeys(variant, modelName);\n  const members = typeList\n    .filter((t) => t !== 'null')\n    .map((t) =>\n      t === 'object'\n        ? modelRef\n        : schemaToTypeRef({ ...variant, type: t, nullable: false }, t === 'array' ? keys.item : keys.value, modelName),\n    );\n  const ref: TypeRef = members.length > 1 ? { kind: 'union', variants: members } : modelRef;\n  return nullable ? asNullable(ref) : ref;\n}\n\nfunction extractEnum(name: string, schema: SchemaObject): Enum {\n  // The members of either spelling (`enumMembersOf`), each with its own\n  // `description` and `deprecated`. A `null` member or `type: 'null'`\n  // variant marks the schema as nullable (OAS 3.1); it is not a value.\n  // Nullability is carried on the `$ref` side via\n  // `activeNullableEnumSchemaNames`, so it is dropped here instead of\n  // emitting a bogus `NULL = \"null\"` member.\n  const values: EnumValue[] = (enumMembersOf(schema) ?? []).map(toEnumValue);\n\n  const rawDefault = schema.default;\n  const def =\n    rawDefault !== undefined && values.some((v) => v.value === rawDefault)\n      ? (rawDefault as string | number)\n      : undefined;\n\n  // The component's own `description` is the enum's, as a model's is its\n  // model's; a lifted inline enum takes its schema's the same way\n  // (`collectInlineEnumFromRef`). Present only when it has content.\n  return {\n    name,\n    ...descriptionEntry(schema.description),\n    values,\n    default: def,\n    ...externalDocsEntry(schema.externalDocs),\n    ...deprecatedEntry(schema),\n    ...schemaExtensionsEntry(schema),\n  };\n}\nfunction extractModel(name: string, schema: SchemaObject, schemas?: Record<string, SchemaObject>): Model {\n  // An `allOf` component, its own `properties` beside the `allOf` read as\n  // its first member (`componentAllOfMembers`).\n  if (schema.allOf) {\n    return extractAllOfModel(name, schema, schemas);\n  }\n\n  const requiredSet = new Set(schema.required ?? []);\n  // The sibling set the field extractor derives for this component too, so\n  // array items and map values are named the same on both sides.\n  const siblings = collectProperties(schema, schemas);\n\n  // Its own `properties`, or — with none — the variants of a pure\n  // `oneOf`/`anyOf` flattened as optional fields (`componentPropertyLedger`,\n  // the ledger the nested-model lookup and the field pass read too). This\n  // handles schemas like UpdateOrganizationMembership which is a oneOf with\n  // mutually exclusive field groups (role_slug vs role_slugs); a variant's\n  // field is optional whatever the schema's own `required` says, as it was.\n  const emptyRequired = new Set<string>();\n  const fields: Field[] = [...componentPropertyLedger(name, schema, schemas).values()].map((entry) =>\n    buildFieldFromSchema(\n      entry.name,\n      declaredComponentProperty(entry),\n      name,\n      entry.unconditional ? requiredSet : emptyRequired,\n      schemas,\n      siblings,\n    ),\n  );\n\n  // When additionalProperties is an object schema alongside properties,\n  // surface it as a catch-all map field so emitters can generate Map<string, T>.\n  if (schema.additionalProperties && typeof schema.additionalProperties === 'object' && schema.properties) {\n    const apKeys = Object.keys(schema.additionalProperties);\n    if (apKeys.length > 0) {\n      const valueType = schemaToTypeRef(schema.additionalProperties as SchemaObject, 'additionalProperties', name);\n      fields.push({\n        name: 'additionalProperties',\n        type: { kind: 'map', valueType },\n        required: false,\n        description: 'Additional properties not captured by named fields',\n      });\n    }\n  }\n\n  // A named union keeps its variants and discriminator beside the merged\n  // fields, the way the same schema written inline keeps them on its union\n  // TypeRef (`namedUnionEntry`). `fields` is untouched, so a consumer that\n  // does not read `variants` sees the model it always did.\n  return {\n    name,\n    description: schema.description,\n    ...externalDocsEntry(schema.externalDocs),\n    fields,\n    ...deprecatedEntry(schema),\n    ...namedUnionEntry(name, schema, schemas),\n    ...constraintsEntry(schema),\n    ...schemaExtensionsEntry(schema),\n  };\n}\n\n/** One non-null variant of a named `oneOf`/`anyOf` component schema (see `namedUnionMembers`). */\ninterface NamedUnionMember {\n  /** The variant as written. */\n  raw: SchemaObject;\n  /** The component schema a `$ref` variant points at (as `extractAllOfModel` resolves its members); `raw` otherwise. */\n  resolved: SchemaObject;\n  /**\n   * The model name the variant is referenced by: an inline object variant's\n   * extracted model (`nameNamedUnionVariants`), a `$ref` variant's component.\n   * `null` for a variant that is neither (a primitive, an inline enum, an\n   * array), which a derived discriminator cannot map.\n   */\n  name: string | null;\n}\n\n/**\n * Everything the parser decides about a named union, decided once and read by\n * both the model (`namedUnionEntry`) and the extractor\n * (`extractNamedUnionVariantModels`), so the variant TypeRefs and the models\n * and enums minted for them agree by construction.\n */\ninterface NamedUnionPlan {\n  compositionKind: 'oneOf' | 'anyOf';\n  /** The non-null variants, in document order; `variants[i]` is built from `members[i]`. */\n  members: NamedUnionMember[];\n  /** The inline object variants' model names (`nameNamedUnionVariants`). */\n  inlineNames: ReadonlyMap<SchemaObject, string>;\n  /**\n   * Every other non-`$ref` variant (a primitive, an inline enum, an array, a\n   * map, an `allOf`, a nested union) as a property of one synthetic object:\n   * `variant_<n>` → schema, where n is the variant's 1-based position among\n   * the non-null variants. Both sides type and extract that object as a\n   * field's parent (`schemaToTypeRef` / `extractInlineModelsFromProperties`\n   * under the union's name), so whatever a variant mints — an enum, an\n   * array's inline items, a map's values, a nested union's variants — is\n   * named `<Union>Variant<n>…` by the one rule the field path uses, and two\n   * variants of the same kind can never share a name.\n   */\n  memberProperties: ReadonlyMap<string, SchemaObject>;\n  /** The same, keyed by variant. */\n  memberContexts: ReadonlyMap<SchemaObject, string>;\n  discriminator?: { property: string; mapping: Record<string, string> };\n}\n\n/**\n * True when a component schema is a named union: a `oneOf`/`anyOf` with no\n * `allOf` and no `properties` of its own. A `oneOf` beside `properties` keeps\n * today's object model (the properties are its fields, the branches are\n * ignored), as does a component that is only a nullable wrapper around one\n * plain inline object — `oneOf: [{ type: object, … }, { type: 'null' }]` —\n * whose merged fields already are the object (an inline wrapper collapses to\n * `nullable<model>`, not to a union). A wrapper around one `$ref`, one\n * primitive, or one object that also admits another type\n * (`type: ['object', 'string']`) is a union of one: the model has nothing\n * else to say about it, and the other type would be lost.\n */\nfunction isNamedUnionSchema(schema: SchemaObject): boolean {\n  if (schema.allOf || (!schema.oneOf && !schema.anyOf)) return false;\n  if (Object.keys(schema.properties ?? {}).length > 0) return false;\n  // A `oneOf`/`anyOf` of string consts is an enum (`isEnumComponentSchema`), not a union.\n  if (isConstUnionEnumSchema(schema)) return false;\n  const nonNull = (schema.oneOf ?? schema.anyOf ?? []).filter((v) => !isNullVariantSchema(v));\n  return !(nonNull.length === 1 && isPlainObjectSchema(nonNull[0]));\n}\n\n/**\n * An inline object that admits nothing but an object (and null): `type:\n * 'object'`, no `type`, `type: ['object', 'null']`, or OAS 3.0 `nullable:\n * true` on one of those. A type list with another member\n * (`['object', 'string']`) is not plain.\n */\nfunction isPlainObjectSchema(schema: SchemaObject | undefined): boolean {\n  if (!isInlineObjectSchema(schema)) return false;\n  const { type } = schema;\n  return !Array.isArray(type) || type.every((t) => t === 'object' || t === 'null');\n}\n\n/**\n * The plan for a named union component, or null for any other schema (see\n * `NamedUnionPlan`). Planned once per extraction (`activeNamedUnionMemo`):\n * the model and the extractor both read it, and building it reads every\n * component and every other union (`namedUnionClaimedShapes`).\n */\nfunction planNamedUnion(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): NamedUnionPlan | null {\n  const memo = activeNamedUnionMemo?.plans.get(schema);\n  if (memo && memo.name === name && memo.schemas === schemas) return memo.plan;\n  const plan = buildNamedUnionPlan(name, schema, schemas);\n  activeNamedUnionMemo?.plans.set(schema, { name, schemas, plan });\n  return plan;\n}\n\nfunction buildNamedUnionPlan(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): NamedUnionPlan | null {\n  if (!isNamedUnionSchema(schema)) return null;\n  const compositionKind: 'oneOf' | 'anyOf' = schema.oneOf ? 'oneOf' : 'anyOf';\n  const inlineNames = nameNamedUnionVariants(name, schema, schemas);\n  const members = namedUnionMembers(schema, inlineNames, schemas);\n  const memberProperties = new Map<string, SchemaObject>();\n  const memberContexts = new Map<SchemaObject, string>();\n  const claimed = namedUnionClaimedShapes(name, schema, schemas);\n  members.forEach(({ raw }, index) => {\n    if (raw.$ref || inlineNames.has(raw)) return;\n    const key = memberContext(`variant_${index + 1}`, raw, name, claimed);\n    memberProperties.set(key, raw);\n    memberContexts.set(raw, key);\n  });\n  const discriminator = namedUnionDiscriminator(schema, compositionKind, members);\n  return {\n    compositionKind,\n    members,\n    inlineNames,\n    memberProperties,\n    memberContexts,\n    ...(discriminator ? { discriminator } : {}),\n  };\n}\n\n/**\n * The `variants`, `compositionKind` and `discriminator` of a named union\n * component (`Model.variants`), or nothing for any other schema. Built the\n * way `schemaToTypeRef` builds the same union inline: a `$ref` variant is a\n * model/enum ref; an inline object variant is referenced by the model\n * extracted for it, a nullable or multi-type one keeping its wrapper\n * (`inlineVariantTypeRef`); a `type: 'null'` variant is dropped; and every\n * other variant is typed as the `variant_<n>` property of the plan's\n * synthetic object, under the union's name, exactly as the extractor\n * materializes it. The spec's own `mapping:` substitutes for an inline\n * variant's name exactly as it does inline (`mapVariantToDiscriminatorEntry`)\n * — on the object member only: the items or values of a multi-type variant's\n * other members are named from the model the plan extracts for it\n * (`inlineNames`, the name `extractNamedUnionVariantModels` builds them\n * under), so the reference and the model agree whatever the mapping says.\n * Derived mappings are read from the same names, so they can only point at\n * models that exist.\n */\nfunction namedUnionEntry(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Pick<Model, 'variants' | 'compositionKind' | 'discriminator'> {\n  const plan = planNamedUnion(name, schema, schemas);\n  if (!plan) return {};\n  const { inlineNames, memberContexts, memberProperties, discriminator } = plan;\n\n  const variants: TypeRef[] = plan.members.map(({ raw }) => {\n    const inlineName = inlineNames.get(raw);\n    if (inlineName !== undefined) {\n      const mappedName = discriminator ? mapVariantToDiscriminatorEntry(raw, discriminator) : null;\n      return inlineVariantTypeRef(raw, inlineName, mappedName ?? inlineName);\n    }\n    if (raw.$ref) return schemaToTypeRef(raw);\n    return schemaToTypeRef(raw, memberContexts.get(raw), name, memberProperties);\n  });\n\n  return { variants, compositionKind: plan.compositionKind, ...(discriminator ? { discriminator } : {}) };\n}\n\n/**\n * The non-null variants of a named union, each with the schema its const\n * values and properties are read from (a `$ref` resolved against the\n * components, so a discriminator pinned inside the referenced schema is\n * seen) and the model name it is referenced by.\n */\nfunction namedUnionMembers(\n  schema: SchemaObject,\n  inlineNames: ReadonlyMap<SchemaObject, string>,\n  schemas: Record<string, SchemaObject> | undefined,\n): NamedUnionMember[] {\n  const members: NamedUnionMember[] = [];\n  for (const raw of schema.oneOf ?? schema.anyOf ?? []) {\n    if (isNullVariantSchema(raw)) continue;\n    let resolved = raw;\n    if (raw.$ref) {\n      const refName = raw.$ref.split('/').pop() ?? '';\n      const target = schemas && Object.hasOwn(schemas, refName) ? schemas[refName] : undefined;\n      if (target) resolved = target;\n    }\n    members.push({ raw, resolved, name: inlineNames.get(raw) ?? resolveVariantModelName(raw) });\n  }\n  return members;\n}\n\n/**\n * Name the inline object variants of a named union component the way a\n * field's union names its own (`nameInlineVariants`), with the union's model\n * name as the base. The base is taken — the union's own model holds it — so\n * variant 0 steps off it like any later variant (`CatPet`, `PetWithLivesLeft`,\n * `Pet1`), and the names in `namedUnionReservedNames` are stepped around.\n */\nfunction nameNamedUnionVariants(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Map<SchemaObject, string> {\n  return nameInlineVariants(schema, name, namedUnionReservedNames(name, schema, schemas), true);\n}\n\n/** The IR name of every component schema being extracted, resolved once per extraction. */\nfunction componentModelNames(): ReadonlySet<string> {\n  if (activeNamedUnionMemo?.componentNames) return activeNamedUnionMemo.componentNames;\n  const names = new Set<string>();\n  for (const key of activeComponentSchemaKeys) names.add(resolveSchemaName(key));\n  if (activeNamedUnionMemo) activeNamedUnionMemo.componentNames = names;\n  return names;\n}\n\n/** `schemaShapeKey`, hashed once per extraction for the schemas the named-union plans compare. */\nfunction namedUnionShapeKey(schema: SchemaObject): string {\n  const cached = activeNamedUnionMemo?.shapes.get(schema);\n  if (cached !== undefined) return cached;\n  const key = schemaShapeKey(schema);\n  activeNamedUnionMemo?.shapes.set(schema, key);\n  return key;\n}\n\n/**\n * The names a named union's inline variants must not take: every component\n * schema's name, so a variant titled like a component never shadows it, and\n * every context-free title another named union component keeps for a variant\n * whose shape differs from the one this union gives the same title — the\n * comparison the field path makes between sibling unions\n * (`reservedInlineNames`, `schemaShapeKey`). Each union is read in isolation\n * against the component names alone, so the decision is symmetric: when\n * `Circle` is `{ radius }` on `Shape` and `{ diameter }` on `Marker`, both\n * fall back to their context-qualified names (`CircleShape`, `CircleMarker`)\n * and neither keeps the bare title; when the shapes are identical, both keep\n * `Circle` and one model is emitted. Context-qualified names carry their own\n * union's name and cannot collide across unions.\n */\nfunction namedUnionReservedNames(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): ReadonlySet<string> {\n  const componentNames = componentModelNames();\n  const reserved = new Set(componentNames);\n  if (!schemas) return reserved;\n\n  const ownShapes = new Map<string, string>();\n  for (const [variant, entry] of nameInlineVariantEntries(schema, name, componentNames, true)) {\n    if (entry.contextFree) ownShapes.set(entry.name, namedUnionShapeKey(variant));\n  }\n  for (const { variant, entry } of otherNamedUnionVariantEntries(name, schema, schemas, componentNames)) {\n    if (entry.contextFree && ownShapes.get(entry.name) !== namedUnionShapeKey(variant)) reserved.add(entry.name);\n  }\n  return reserved;\n}\n\n/**\n * The inline object variants of every other named union component, each\n * with the name it would keep, read in isolation against the component names\n * alone (no cross-union reservations), so every union sees the others the\n * same way and no two can chase each other's names. Each union's entries are\n * named once per extraction (`activeNamedUnionMemo`): every other union's\n * plan reads them, twice.\n */\nfunction otherNamedUnionVariantEntries(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  componentNames: ReadonlySet<string>,\n): Array<{ variant: SchemaObject; entry: InlineVariantName }> {\n  const entries: Array<{ variant: SchemaObject; entry: InlineVariantName }> = [];\n  for (const [key, other] of Object.entries(schemas)) {\n    if (other === schema || !isNamedUnionSchema(other)) continue;\n    const otherName = resolveSchemaName(key);\n    if (otherName === name) continue;\n    let otherEntries = activeNamedUnionMemo?.variantEntries.get(other);\n    if (!otherEntries) {\n      otherEntries = nameInlineVariantEntries(other, otherName, componentNames, true);\n      activeNamedUnionMemo?.variantEntries.set(other, otherEntries);\n    }\n    for (const [variant, entry] of otherEntries) entries.push({ variant, entry });\n  }\n  return entries;\n}\n\n/**\n * Every model or enum name already spoken for when a named union's\n * `variant_<n>` members mint theirs, with the shape of each claimant: every\n * component schema (its own shape), and every inline object variant of every\n * other named union (`otherNamedUnionVariantEntries`). A claimant whose\n * shape is unknown (no component map) is recorded as `null`, which never\n * counts as identical.\n */\nfunction namedUnionClaimedShapes(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Map<string, Array<string | null>> {\n  const claimed = new Map<string, Array<string | null>>();\n  const claim = (claimant: string, shape: string | null): void => {\n    if (claimant === name) return;\n    claimed.set(claimant, [...(claimed.get(claimant) ?? []), shape]);\n  };\n  if (!schemas) {\n    for (const claimant of componentModelNames()) claim(claimant, null);\n    return claimed;\n  }\n  for (const [key, other] of Object.entries(schemas)) claim(resolveSchemaName(key), namedUnionShapeKey(other));\n  for (const { variant, entry } of otherNamedUnionVariantEntries(name, schema, schemas, componentModelNames())) {\n    claim(entry.name, namedUnionShapeKey(variant));\n  }\n  return claimed;\n}\n\n/**\n * The synthetic property name a non-object variant of a named union is typed\n * and extracted under: `base` (`variant_<n>`) unless a name it would mint\n * under it (`mintedInlineNameEntries`: `PetVariant1` for an inline enum, an\n * array's inline items or a map's inline values, a nested union's variants)\n * is already claimed by a component or by another union's variant of a\n * different shape (`claimed`). An identical shape is shared, as array items\n * share a same-shaped sibling's model; otherwise the context steps exactly as\n * an array's or map's does beside a claiming sibling\n * (`firstFreeElementContext`): `variant_1_item` / `variant_1_value`\n * (`PetVariant1Item`, `PetVariant1Value`), then `variant_1_array_item` /\n * `variant_1_member_value`, then numbered — stopping as soon as a candidate\n * mints the same names as the one before it (a context-free name no context\n * can escape) and at the attempt cap. Both sides read the chosen context\n * from the plan, so every name nested under a stepped variant moves with it.\n */\nfunction memberContext(\n  base: string,\n  variant: SchemaObject,\n  unionName: string,\n  claimed: ReadonlyMap<string, ReadonlyArray<string | null>>,\n): string {\n  const mint = (candidate: string): string[] =>\n    mintedInlineNameEntries(candidate, variant, unionName)\n      .filter((entry) => !entry.contextFree)\n      .map((entry) => entry.name);\n  const own = mint(base);\n  if (own.length === 0) return base;\n  const rivals = own.flatMap((minted) => claimed.get(minted) ?? []);\n  if (rivals.length === 0) return base;\n  const shape = namedUnionShapeKey(mintingSchema(variant));\n  if (rivals.every((rival) => rival === shape)) return base;\n  // An array in any spelling (`isArraySchema`: a bare `items`, a nullable\n  // type list) steps with `_item`, as the doc says it does; a map with `_value`.\n  const kind = isArraySchema(variant) ? 'item' : 'value';\n  return firstFreeElementContext(base, kind, new Set(claimed.keys()), mint, own).context;\n}\n\n/**\n * The schema whose shape a non-object variant's minted name stands for: an\n * array's items, a map's values, else the variant itself — read with its\n * nullable wrapper removed, as `elementContextDecision` reads an array's\n * items against a claiming sibling, so a nullable array of the claimant's\n * shape shares the claimant's model instead of stepping around it.\n */\nfunction mintingSchema(variant: SchemaObject): SchemaObject {\n  const bare = unwrapNullableSchema(variant);\n  if (bare.items && isArraySchema(bare)) return mintingSchema(bare.items);\n  if (bare.type === 'object' && !bare.properties) {\n    const value = mapValueSchema(bare);\n    if (value) return mintingSchema(value);\n  }\n  return bare;\n}\n\n/**\n * True for a `components/schemas` entry the parser reads as an array\n * component: a schema `isArraySchema` accepts — `type: 'array'`, an OAS 3.1\n * type list `['array', 'null']`, OAS 3.0 `nullable: true` beside `type:\n * 'array'`, or `items` with no `type` — that declares `items`. An `enum:`\n * list or a `oneOf`/`anyOf` beside the array is read first by\n * `classifyInlineSchema`, so such a schema is an enum or a named union here\n * as it is everywhere else. A `type: 'array'` with no `items` is not an array\n * component: `schemaToTypeRef` types it as unknown, with a warning, so it\n * keeps the fieldless model it always became rather than warning at every\n * reference.\n */\nexport function isArrayComponentSchema(schema: SchemaObject): boolean {\n  return isArraySchema(schema) && schema.items !== undefined;\n}\n\n/**\n * Whether a `components/schemas` entry is read as an array component: an\n * array schema itself (`isArrayComponentSchema`), or one `schemaToTypeRef`\n * types as an array through the readings it makes of a `$ref` and an\n * `allOf` — a bare `$ref` to one; an `allOf` read as a plain reference\n * (`readInlineAllOf`: `$ref` members with nothing inline beside them —\n * `allOf: [{ $ref: Pets }]`, `allOf: [{ $ref: Pets }, { maxItems: 10 }]`),\n * read as its first `$ref` member; an `allOf` of one member, read as that\n * member (`unwrappedAllOfMember`) — followed through aliases of aliases, so a\n * `$ref` to the alias resolves to the array exactly as the same schema\n * written on a field does. `properties` written beside the composition are\n * folded in first (`foldSiblingProperties`), as `schemaToTypeRef` folds\n * them. A chain that returns to an entry it has visited names no array:\n * such an entry stays the fieldless model it always became, as an alias of\n * an object component does.\n */\nexport function isArrayComponentEntry(\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  seen: Set<SchemaObject> = new Set(),\n): boolean {\n  if (isArrayComponentSchema(schema)) return true;\n  if (seen.has(schema)) return false;\n  seen.add(schema);\n  const folded = foldSiblingProperties(schema);\n  const aliasOf = (ref: string | undefined): boolean => {\n    const key = ref === undefined ? undefined : componentKeyOf(ref);\n    const aliased = key === undefined ? undefined : schemas[key];\n    return aliased !== undefined && isArrayComponentEntry(aliased, schemas, seen);\n  };\n  if (folded.$ref) return aliasOf(folded.$ref);\n  if (classifyInlineSchema(folded) !== 'allOf' || !folded.allOf) return false;\n  const reading = readInlineAllOf(folded.allOf, folded, schemas);\n  if (reading === 'reference') return aliasOf(folded.allOf.find((member) => member.$ref)?.$ref);\n  if (reading === 'unwrapped') {\n    return isArrayComponentEntry(unwrappedAllOfMember(folded, folded.allOf[0]), schemas, seen);\n  }\n  return false;\n}\n\n/** The `components/schemas` key a `$ref` names, or `undefined` for a `$ref` into another section of the document. */\nfunction componentKeyOf(ref: string): string | undefined {\n  const match = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n  return match?.[1];\n}\n\n/**\n * The plan for an array component (`ArrayComponentPlan`): the synthetic\n * property its schema is typed and extracted as, under the component's\n * resolved name. The base is `item`, so inline object items are\n * `<Component>Item`, an inline enum `<Component>Item`, the objects of a\n * nested array or map `<Component>Item` as well, and whatever those hold\n * `<Component>Item…`, by the one rule a field's inline models follow. Every\n * name the whole tree mints under a context is read off a rehearsal of the\n * extraction itself (`arrayComponentMints`), so an object nested under the\n * item model (`PetsItemOwner`) or an enum a nested field holds counts\n * exactly as the item model does. When any of them is already claimed for a\n * different shape (`arrayComponentClaims`: any name any extraction pass\n * takes from another entry — its model, enum or array, a discriminated or\n * named-union variant, an object its fields mint, their nested objects and\n * lifted enums — or another array component's tree), the context steps\n * exactly as a named union's `variant_<n>` does\n * (`firstFreeElementContext`): `item_item` (`<Component>ItemItem…`), then\n * `item_array_item`, then numbered, until no name under it is claimed, and\n * every name nested under the tree moves with it. A claimant of the\n * identical shape — the same fields and limits for a model, the same\n * members for an enum — is shared instead, and the tree references it.\n * `own` is the tree's names under `item`; `others` the names every other\n * tree claims — what the plans decided before this one settled on, what the\n * plans after it would mint under `item` — so a stepped tree never lands on\n * a name another tree keeps or steps to, in either direction.\n */\nfunction planArrayComponent(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  own: ArrayComponentMints,\n  others: ReadonlyMap<string, ArrayComponentMints>,\n  minted: ReadonlyMap<string, ReadonlyMap<string, readonly string[]>>,\n): string {\n  const claims = arrayComponentClaims(others, minted);\n  const contested = [...mintedShapes(own)].some(([minted, shape]) =>\n    (claims.get(minted) ?? []).some((rival) => rival !== shape),\n  );\n  if (!contested) return 'item';\n  const names = (mints: ArrayComponentMints): string[] => [...mintedShapes(mints).keys()];\n  return firstFreeElementContext(\n    'item',\n    'item',\n    new Set(claims.keys()),\n    (candidate) => names(arrayComponentMints(name, schema, schemas, candidate)),\n    names(own),\n  ).context;\n}\n\n/** The rounds `extractSchemas` gives the array components' plans to settle; two suffice unless trees chase each other's names. */\nconst MAX_ARRAY_COMPONENT_ROUNDS = 8;\n\n/** The shape key of every name a tree mints: a model's fingerprint, an inline enum's members. */\nfunction mintedShapes(mints: ArrayComponentMints): Map<string, string> {\n  const shapes = new Map<string, string>();\n  for (const model of mints.models) shapes.set(model.name, modelShapeKey(model));\n  for (const [enumName, values] of mints.enums) shapes.set(enumName, enumShapeOf(values));\n  return shapes;\n}\n\n/** The shape a model stands for when a name is contested: its fingerprint, the key every clash check in the parser reads. */\nfunction modelShapeKey(model: Model): string {\n  return `model:${modelFingerprint(model)}`;\n}\n\n/** The shape an enum stands for when a name is contested: its members, each with its deprecation. */\nfunction enumShapeOf(values: readonly EnumValue[]): string {\n  return `enum:${enumShapeKey(values)}`;\n}\n\n/**\n * Every model and inline enum an array component's items would mint under\n * `context`: a rehearsal of both sides — the extractor\n * (`extractInlineModelsFromProperties`) for the models, `schemaToTypeRef`\n * for the inline enums the items are or hold, read off the TypeRef it builds\n * and the fields of the models built — so the names are the ones the real\n * extraction produces, with no second copy of the naming rules to keep in\n * step. The models are built with every array component provisionally\n * registered (`extractSchemas`), so their fingerprints read a `$ref` to one\n * as the array the real pass types; the enums are read with none registered\n * (`withoutArrayComponents`), so an enum another component's items hold is\n * never counted as this tree's own. The rehearsal is silent and leaves no\n * trace (`rehearse`).\n */\nfunction arrayComponentMints(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  context: string,\n): ArrayComponentMints {\n  return rehearse(() => {\n    const extract = (): Model[] => {\n      const models: Model[] = [];\n      extractInlineModelsFromProperties({ properties: { [context]: schema } }, models, name, schemas);\n      return models;\n    };\n    const models = extract();\n    const enums = withoutArrayComponents(() =>\n      liftedEnums([\n        schemaToTypeRef(schema, context, name, new Map([[context, schema]])),\n        ...extract().flatMap((model) => collectModelTypeRefs(model)),\n      ]),\n    );\n    return { models, enums };\n  });\n}\n\n/** Every inline enum `refs` hold — an `EnumRef` carrying `values` — by name, with its members; the first occurrence of a name decides, as the lift does. */\nfunction liftedEnums(refs: readonly TypeRef[]): Map<string, EnumValue[]> {\n  const enums = new Map<string, EnumValue[]>();\n  for (const ref of refs) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (r.values && !enums.has(r.name)) enums.set(r.name, enumValuesOf(r));\n      },\n    });\n  }\n  return enums;\n}\n\n/**\n * The plan of an array component under `context`: what `extractSchemas`\n * registers for a tree while the plans are decided — so a `$ref` to it\n * resolves to its array in every rehearsal, as the real pass types it, under\n * the names the tree carries at that point — and, once a round moves\n * nothing, for good.\n */\nfunction arrayComponentPlan(key: string, schema: SchemaObject, context: string): ArrayComponentPlan {\n  return {\n    key,\n    name: resolveSchemaName(key),\n    schema,\n    context,\n    properties: new Map([[context, schema]]),\n    warnedSelfReference: false,\n  };\n}\n\n/**\n * Run `fn` with no array component registered, so a `$ref` to one is a\n * plain model reference that mints nothing: the way the names a tree mints\n * are read, so another component's items are never counted among them.\n */\nfunction withoutArrayComponents<T>(fn: () => T): T {\n  const plans = activeArrayComponentPlans;\n  activeArrayComponentPlans = new Map();\n  try {\n    return fn();\n  } finally {\n    activeArrayComponentPlans = plans;\n  }\n}\n\n/**\n * Run `fn` as a rehearsal whose output is discarded: `console.warn` is\n * silenced, and the memory of which unions' fold warnings were already\n * reported is set aside and restored, so every warning the schema deserves\n * is printed once, by the extraction that keeps the models.\n */\nfunction rehearse<T>(fn: () => T): T {\n  const warn = console.warn;\n  const reported = reportedUncarriedProperties;\n  console.warn = () => {};\n  reportedUncarriedProperties = new WeakSet();\n  try {\n    return fn();\n  } finally {\n    console.warn = warn;\n    reportedUncarriedProperties = reported;\n  }\n}\n\n/**\n * Every name a `components/schemas` entry takes when it is extracted, each\n * with the shape(s) it stands for, read off a rehearsal of the passes that\n * take them rather than a list of those passes kept in step by hand: the\n * entry's own name — a model's fingerprint (`extractModel`), an enum's\n * members (`extractEnum`), or `'array'` for an array component, a shape no\n * model or enum can share — its discriminated allOf+oneOf variants\n * (`extractDiscriminatedAllOfVariantModels`), its named-union variants and\n * `variant_<n>` members (`extractNamedUnionVariantModels`), the inline\n * models its fields mint (`extractInlineModelsFromSchemas`, the field pass),\n * everything nested under any of those, and every inline enum those\n * models' fields hold — so an array component's plan steps around exactly\n * the names the real passes will take, and an `Event` whose variant pins\n * `type: 'pets_item'` keeps its `PetsItem` while `Pets`'s items step. A name\n * two passes mint for one entry carries both shapes. The models are built\n * with every array component provisionally registered, so a field that is a\n * `$ref` to one is fingerprinted as the array the real pass types; the\n * enums are read with none registered (`withoutArrayComponents`), so an\n * enum another component's items hold is never claimed for this entry. An\n * array component's items are not read here: their names come from its plan\n * (`others`), under the context it settles on.\n */\nfunction componentMints(\n  key: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n): ReadonlyMap<string, readonly string[]> {\n  const name = resolveSchemaName(key);\n  return rehearse(() => {\n    const shapes = new Map<string, string[]>();\n    const claim = (minted: string, shape: string): void => {\n      shapes.set(minted, [...(shapes.get(minted) ?? []), shape]);\n    };\n    if (isEnumComponentSchema(schema)) {\n      claim(name, enumShapeOf(extractEnum(name, schema).values));\n      return shapes;\n    }\n    if (isArrayComponentEntry(schema, schemas)) {\n      claim(name, 'array');\n      return shapes;\n    }\n    const extract = (): Model[] => [\n      extractModel(name, schema, schemas),\n      ...extractDiscriminatedAllOfVariantModels(schema, name, schemas),\n      ...extractNamedUnionVariantModels(schema, name, schemas),\n      ...extractInlineModelsFromSchemas({ [key]: schema }),\n    ];\n    for (const model of extract()) claim(model.name, modelShapeKey(model));\n    const enums = withoutArrayComponents(() => liftedEnums(extract().flatMap((model) => collectModelTypeRefs(model))));\n    for (const [enumName, values] of enums) claim(enumName, enumShapeOf(values));\n    return shapes;\n  });\n}\n\n/**\n * Every name an array component's item tree must not take for a shape of\n * its own, each with the shape(s) it stands for: every name every other\n * entry takes (`minted`, see `componentMints`) and every model and enum\n * every other array component's tree mints (`others`: settled or isolated,\n * as `planArrayComponent` says). A claimant of the identical shape is\n * shared, so two trees that mint one name for one shape keep it and one\n * model is emitted.\n */\nfunction arrayComponentClaims(\n  others: ReadonlyMap<string, ArrayComponentMints>,\n  minted: ReadonlyMap<string, ReadonlyMap<string, readonly string[]>>,\n): Map<string, string[]> {\n  const claims = new Map<string, string[]>();\n  const claim = (claimant: string, shape: string): void => {\n    claims.set(claimant, [...(claims.get(claimant) ?? []), shape]);\n  };\n  for (const names of minted.values()) {\n    for (const [name, shapes] of names) for (const shape of shapes) claim(name, shape);\n  }\n  for (const mints of others.values()) {\n    for (const [name, shape] of mintedShapes(mints)) claim(name, shape);\n  }\n  return claims;\n}\n\n/**\n * The models an array component's items reference that nothing else\n * materializes — an inline object item, the object variants of an\n * `items.oneOf`, the objects of a nested array or map, an `allOf`, and\n * everything nested under them — extracted by the field extractor from the\n * plan's synthetic property under the component's resolved name, exactly as\n * `arrayComponentTypeRef` types it. Nothing for an alias of another array\n * component, whose `$ref` mints nothing.\n */\nfunction extractArrayComponentModels(key: string, schemas: Record<string, SchemaObject>): Model[] {\n  const plan = activeArrayComponentPlans.get(key);\n  if (!plan) return [];\n  const models: Model[] = [];\n  extractInlineModelsFromProperties({ properties: Object.fromEntries(plan.properties) }, models, plan.name, schemas);\n  return models;\n}\n\n/**\n * The TypeRef a `$ref` to the array component under `key` resolves to: the\n * array the component declares, built by `schemaToTypeRef` from the plan's\n * synthetic property under the component's resolved name — so a nullable\n * type list or OAS 3.0 flag on the component wraps it in `nullable`, an\n * alias (`isArrayComponentEntry`) resolves to the component it names, `$ref`\n * items stay the references they are (to a model, an enum, or another array\n * component, which resolves in turn), and inline items are named\n * `<Component>Item…` as `extractArrayComponentModels` builds them. A fresh\n * TypeRef per reference, since later passes rename references in place. A\n * component reached again while its own reference is being built — `Tree:\n * { type: 'array', items: { $ref: Tree } }`, directly or through another\n * array component or an alias — has no finite type in the IR: that inner\n * reference is typed as unknown, with one warning per component, naming the\n * key as the document writes it. `undefined` for any other key.\n */\nfunction arrayComponentTypeRef(key: string): TypeRef | undefined {\n  const plan = activeArrayComponentPlans.get(key);\n  if (!plan) return undefined;\n  if (resolvingArrayComponents.has(key)) {\n    if (!plan.warnedSelfReference) {\n      plan.warnedSelfReference = true;\n      console.warn(\n        `[oagen] Warning: Array component \"${key}\" refers to itself through its items — the inner reference is typed as unknown`,\n      );\n    }\n    return { kind: 'primitive', type: 'unknown' };\n  }\n  resolvingArrayComponents.add(key);\n  try {\n    return schemaToTypeRef(plan.schema, plan.context, plan.name, plan.properties);\n  } finally {\n    resolvingArrayComponents.delete(key);\n  }\n}\n\n/**\n * Whether `schema` is a `$ref` to an array component — by the key the `$ref`\n * names, as `schemaToTypeRef` resolves it — under any nullable wrapper\n * `unwrapNullableSchema` strips, so a reader that asks whether a property is\n * an array from the document (`detectListEnvelope`, `buildFieldFromSchema`)\n * answers for a reference as `schemaToTypeRef` types it. False outside an\n * extraction, as a `$ref` to an enum component is a model reference there.\n */\nexport function isArrayComponentRef(schema: SchemaObject | undefined): boolean {\n  if (!schema) return false;\n  const { $ref } = unwrapNullableSchema(schema);\n  if (!$ref) return false;\n  const segments = $ref.split('/');\n  return activeArrayComponentPlans.has(segments[segments.length - 1]);\n}\n\n/**\n * The discriminator of a named union, resolved from the same four sources\n * `schemaToTypeRef` reads for an inline union, in the same order, with a\n * `$ref` variant's const read from the component it points at:\n *   1. An explicit `discriminator:` with a `mapping:` — the spec's own, each\n *      target reduced to the IR model name it refers to (the last `$ref`\n *      segment through `resolveSchemaName`, so `schemaNameTransform` applies,\n *      as it does to every mapping value `Model.discriminator` carries). An\n *      entry naming a schema outside the variant list is kept as written.\n *   2. An explicit `discriminator:` without `mapping:` — each variant's const\n *      on the property paired with its model name; `{}` when any variant\n *      pins none or is unnamed, as `deriveInlineVariantMapping` leaves it.\n *   3./4. No keyword, `oneOf` only — when every variant is named, the first\n *      property the first variant pins whose values are distinct across all\n *      of them, with that mapping (`titleMappedDiscriminatorProperty` /\n *      `deriveConstNamingDiscriminator` for an inline union). A constant\n *      every variant shares (`version: 'v1'`) is passed over, not taken as\n *      proof there is no discriminator; an unnamed variant is no signal, and\n *      an `anyOf` is never discriminated implicitly.\n */\nfunction namedUnionDiscriminator(\n  schema: SchemaObject,\n  compositionKind: 'oneOf' | 'anyOf',\n  members: readonly NamedUnionMember[],\n): { property: string; mapping: Record<string, string> } | undefined {\n  if (schema.discriminator) {\n    const property = schema.discriminator.propertyName;\n    const explicit = Object.entries(schema.discriminator.mapping ?? {});\n    const mapping: Record<string, string> =\n      explicit.length > 0\n        ? Object.fromEntries(\n            explicit.map(([value, target]) => [value, resolveSchemaName(target.split('/').pop() ?? '')]),\n          )\n        : (namedUnionConstMapping(members, property) ?? {});\n    return { property, mapping };\n  }\n  if (compositionKind !== 'oneOf' || members.length < 2) return undefined;\n  if (members.some((m) => m.name === null)) return undefined;\n  const first = members[0];\n  if (!first) return undefined;\n  for (const property of Object.keys(getEffectiveProperties(first.resolved))) {\n    const mapping = namedUnionConstMapping(members, property);\n    if (mapping) return { property, mapping };\n  }\n  return undefined;\n}\n\n/**\n * `property`'s const value on every member paired with the member's model\n * name, or null when any member is unnamed, pins no string const on the\n * property (through its `allOf` wrappers, like an allOf+oneOf variant), or\n * repeats another member's value. Collected in a Map, so a value spelled like\n * an inherited property (`constructor`, `toString`) is neither mistaken for a\n * duplicate nor lost; the result has every value as an own key.\n */\nfunction namedUnionConstMapping(members: readonly NamedUnionMember[], property: string): Record<string, string> | null {\n  if (members.length === 0) return null;\n  const mapping = new Map<string, string>();\n  for (const member of members) {\n    if (member.name === null) return null;\n    const value = getEffectiveConstPropertyValue(member.resolved, property);\n    if (value === null || mapping.has(value)) return null;\n    mapping.set(value, member.name);\n  }\n  return Object.fromEntries(mapping);\n}\n\n/**\n * The models a named union component's variants reference that nothing else\n * materializes, extracted by the field extractor so every object shape\n * `schemaToTypeRef` references — a nested object with or without `type`, an\n * array's or map's inline items, an `allOf`, a nested union — is\n * materialized under the name the reference uses: each inline object variant\n * under the name `nameNamedUnionVariants` gave it, with everything nested\n * under it and, for a multi-type variant, the members of its other types,\n * exactly as the extractor's own union branch does; and the plan's synthetic\n * object of every other variant (`variant_<n>`), extracted under the union's\n * name as the TypeRefs were typed. Nothing for a schema that is not a named\n * union.\n */\nfunction extractNamedUnionVariantModels(\n  schema: SchemaObject,\n  name: string,\n  schemas?: Record<string, SchemaObject>,\n): Model[] {\n  const plan = planNamedUnion(name, schema, schemas);\n  if (!plan) return [];\n  const models: Model[] = [];\n  for (const [variant, variantName] of plan.inlineNames) {\n    models.push(buildInlineModel(variantName, variant, schemas));\n    extractInlineModelsFromProperties(variant, models, variantName, schemas);\n    extractInlineModelsFromProperties(\n      { properties: variantMemberSchemas(variant, variantName) },\n      models,\n      variantName,\n      schemas,\n    );\n  }\n  if (plan.memberProperties.size > 0) {\n    extractInlineModelsFromProperties({ properties: Object.fromEntries(plan.memberProperties) }, models, name, schemas);\n  }\n  return models;\n}\n\n/** A dispatcher's discriminator: the property every variant pins, and the model each value selects. */\ntype AllOfDiscriminator = { property: string; mapping: Record<string, string> };\n\n/**\n * The variants of the union a schema carries — `oneOf`, else `anyOf` — or\n * `undefined` for a schema carrying none. The one keyword test every\n * reader of a component's `allOf` + union applies: the member reader that\n * detects a dispatcher or flattens the variants (`readComponentAllOfMember`),\n * the variant builder (`extractDiscriminatedAllOfVariantModels`, its axis\n * and its variant loop), a pure union's flattening\n * (`componentPropertyLedger`) and a variant's nested unions\n * (`flattenVariantForExtraction`) — so a union detected as a dispatcher is\n * the union whose variant models are built, whichever keyword spells it\n * (workos/oagen#359 review: an `anyOf` axis was dispatched but its variants\n * were not built, and the mapping named a model nothing created).\n */\nexport function unionVariantsOf(schema: SchemaObject): SchemaObject[] | undefined {\n  return schema.oneOf ?? schema.anyOf;\n}\n\n/**\n * Read one member of a component's `allOf` into `ledger` and `required`,\n * each declaration with its provenance (`declareProperty`). A `$ref` member\n * is resolved to its component, through a chain of references; a component\n * met again on the chain declares nothing more. An `allOf` member — a\n * component composed with `allOf`, or an inline wrapper — is read by\n * `readComponentAllOf`, so a declaration it makes under a `oneOf`/`anyOf`\n * variant stays branch-only however deep it sits; its own discriminator, if\n * any, is its own model's and is not returned (the model reading it carries\n * the base fields only). Every member contributes its own `properties` as\n * always-applying and its own `required` — beside a `oneOf`/`anyOf` too. A\n * member's `oneOf`/`anyOf` with exactly one non-null variant beside `null`\n * is a nullable wrapper, not a union — decided by `nullableUnionBranch`, the\n * definition `unwrapNullableSchema` collapses by, which `mergeAllOfMembers`\n * reads an inline member through and the envelope collector reads every\n * member through (`resolveBareSchema`) — and that variant is read as one\n * more member, in this member's own capacity: `{ oneOf: [{ $ref: Base }, {\n * type: 'null' }] }` applies `Base` whole, its `$ref` followed and its\n * `required` read, since an instance that is not null is a `Base` and\n * beside an object member it is never null (workos/oagen#308: read as a\n * union, `Base`'s `has_more` ended the operation's iteration but was\n * missing from the model); the wrapper itself is recorded as read, so a\n * component that wraps a reference to itself ends there. A member's\n * `oneOf`/`anyOf` whose variants pin one property to distinct consts is a\n * dispatcher (`detectAllOfVariantDiscriminator`): its variants' properties\n * are not read, and the discriminator is returned; otherwise every\n * variant's properties are read as branch-only, and a variant's `required`\n * is not read, since its properties are present only on that branch. With\n * `readVariants` false the union is not read at all — the dispatcher base\n * reads the variant axis for its own properties only — while a nullable\n * wrapper, never a variant axis, is still applied. Shared by\n * `extractAllOfModel` and the dispatcher base of\n * `extractDiscriminatedAllOfVariantModels`, so the two read a member alike.\n */\nfunction readComponentAllOfMember(\n  name: string,\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  ledger: Map<string, PropertyDeclarations>,\n  required: Set<string>,\n  seen: Set<SchemaObject>,\n  readVariants = true,\n): AllOfDiscriminator | undefined {\n  const resolved = followMemberRefs(member, schemas, seen);\n  if (!resolved) return undefined;\n  if (resolved.allOf) {\n    readComponentAllOf(name, resolved, schemas, ledger, required, seen);\n    return undefined;\n  }\n  // The member's own `properties` and `required` always apply, whether or\n  // not a `oneOf`/`anyOf` sits beside them (workos/oagen#359 review: a\n  // member `{ properties: { x }, oneOf: […] }`, inline or a `$ref` to such a\n  // component, lost `x`, while the same schema as a body kept it).\n  for (const r of resolved.required ?? []) required.add(r);\n  for (const [key, value] of Object.entries(resolved.properties ?? {})) {\n    if (value) declareProperty(ledger, key, value, null, false);\n  }\n  // A nullable wrapper is its one non-null variant, read as one more member\n  // in this member's own capacity (`nullableUnionBranch`); the wrapper is\n  // recorded so a component that wraps a reference to itself ends here.\n  const branch = nullableUnionBranch(resolved);\n  if (branch) {\n    if (seen.has(resolved)) return undefined;\n    seen.add(resolved);\n    return readComponentAllOfMember(name, branch, schemas, ledger, required, seen, readVariants);\n  }\n  const variants = unionVariantsOf(resolved);\n  if (!variants || !readVariants) return undefined;\n  // Detect discriminated union: every variant pins the same property to a\n  // distinct const value (e.g. EventSchema where each variant has event: const).\n  // When detected, store the discriminator instead of flattening variant fields —\n  // the base allOf schema already captures the common fields.\n  const discriminator = detectAllOfVariantDiscriminator(variants, name);\n  if (discriminator) return discriminator;\n  // Flatten oneOf/anyOf variant fields into the parent model as optional\n  // fields. This handles the common allOf + oneOf pattern where the spec\n  // uses mutually exclusive variant groups (e.g. password vs password_hash).\n  for (const variant of variants) {\n    for (const [key, value] of Object.entries(variant.properties ?? {})) {\n      if (value) declareProperty(ledger, key, value, null, true);\n    }\n  }\n  return undefined;\n}\n\n/**\n * Read a component schema's `allOf` — its own `properties` and `required`\n * first (`componentAllOfMembers`), then each member through\n * `readComponentAllOfMember` — into `ledger` and `required`, and return the\n * discriminator a direct `oneOf`/`anyOf` member declares, if any. A schema\n * reached again on the chain declares nothing more (`seen`), so a component\n * that names itself, or two members naming one component, terminate.\n */\nfunction readComponentAllOf(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  ledger: Map<string, PropertyDeclarations>,\n  required: Set<string>,\n  seen: Set<SchemaObject> = new Set(),\n): AllOfDiscriminator | undefined {\n  if (seen.has(schema)) return undefined;\n  seen.add(schema);\n  let discriminator: AllOfDiscriminator | undefined;\n  for (const member of componentAllOfMembers(schema)) {\n    discriminator = readComponentAllOfMember(name, member, schemas, ledger, required, seen) ?? discriminator;\n  }\n  // The component's own `required`: carried by its own member when it\n  // declares properties, and read here when it only names inherited ones\n  // (`Pup: { allOf: [{ $ref: Dog }], required: [breed] }`).\n  for (const r of schema.required ?? []) required.add(r);\n  return discriminator;\n}\n\n/**\n * The schema that types a property a component declares: the always-applying\n * declaration `declareProperty` settles on — the first that declares a type,\n * a typeless one only annotating it (`combineDeclarations`) — else the first\n * branch's, carrying the extensions every branch agrees on in place of its\n * own (`agreedExtensions`, the one agreement rule a property only variants\n * declare follows, inline or under a component; workos/oagen#369 review: a\n * component's `kind` took the first variant's `x-since` while the inline\n * twin left a disputed key off).\n * A component flattens a union's branches as written; the union of distinct\n * branch declarations `mergeAllOfMembers` builds for an inline `allOf` is not\n * built here, since no pass would materialize its inline variants under a\n * component. Read over `componentPropertyLedger` by every pass that builds a\n * field or a model nested under one, so they agree on the declaration.\n */\nexport function declaredComponentProperty(entry: PropertyDeclarations): SchemaObject {\n  if (entry.unconditional) return entry.unconditional.schema;\n  return withAgreedExtensions(entry.conditional[0]!, agreedExtensions(entry.conditional));\n}\n\n/**\n * The model of a component schema composed with `allOf` (`extractModel`).\n * The members are read in document order (`readComponentAllOf`), the\n * component's own `properties` and `required` first as one more member\n * (`componentAllOfMembers`); a `$ref` member's component is read the same\n * way, its own properties and then its members, so a chain\n * (`Puppy → Dog → Pet`) carries every level's own properties. Every field is\n * typed under the component's own name with one sibling set\n * (`collectProperties`), from the one declaration\n * `declaredComponentProperty` picks: the always-applying declaration\n * `declareProperty` settles on — the first that declares a type, the\n * component's own first, a typeless one only annotating it — whatever a\n * `oneOf`/`anyOf` variant declares\n * before or after it and at whatever depth — the precedence\n * `declareProperty` gives `mergeAllOfMembers` too — and `required` is the\n * union of every always-applying member's list and the component's own; a\n * variant's `required` is not read. A `oneOf`/`anyOf` member whose variants\n * pin one property to distinct consts makes the model a dispatcher\n * (`detectAllOfVariantDiscriminator`; its variants are built by\n * `extractDiscriminatedAllOfVariantModels`); otherwise the variants' inline\n * properties are flattened in as optional fields.\n */\nfunction extractAllOfModel(name: string, schema: SchemaObject, schemas?: Record<string, SchemaObject>): Model {\n  // One sibling set for every field of the composed model, nested `allOf`\n  // levels included, matching what the field extractor derives for it.\n  const siblings = collectProperties(schema, schemas);\n  const ledger = new Map<string, PropertyDeclarations>();\n  const requiredSet = new Set<string>();\n  const discriminator = readComponentAllOf(name, schema, schemas, ledger, requiredSet);\n  const fields = [...ledger.values()].map((entry) =>\n    buildFieldFromSchema(entry.name, declaredComponentProperty(entry), name, requiredSet, schemas, siblings),\n  );\n\n  return {\n    name,\n    description: schema.description,\n    ...externalDocsEntry(schema.externalDocs),\n    fields,\n    ...(discriminator ? { discriminator } : {}),\n    // Deprecation is the wrapper's own: a member's flag is not read — a `$ref`\n    // member's stays on the referenced model — as `Field.deprecated` ignores\n    // it on an allOf field.\n    ...deprecatedEntry(schema),\n    // The wrapper's own keywords conjoined with its inline members'; `$ref`\n    // members keep theirs on the referenced model.\n    ...constraintsEntry(schema),\n    // The wrapper's own extensions, as its flag and link: a member's stay on\n    // that member, a `$ref` member's on its component.\n    ...schemaExtensionsEntry(schema),\n  };\n}\n\n/**\n * Walk through `allOf` wrappers to collect the effective top-level properties\n * of a schema. Stops at `oneOf` / `anyOf` boundaries — those are different\n * variant axes, not part of the same flat object.\n *\n * Used by `detectAllOfVariantDiscriminator` and `deriveDiscriminatedVariantName`\n * so a oneOf variant of the form `{ allOf: [{ properties: { … } }, { oneOf: […] }] }`\n * still surfaces its top-level `properties` (in particular its discriminator\n * `const`) instead of being treated as having none.\n */\nfunction getEffectiveProperties(schema: SchemaObject): Record<string, SchemaObject> {\n  // Collected in a `Map` and returned through `Object.fromEntries`, so a\n  // property named `__proto__` is an own entry rather than the prototype.\n  const props = new Map<string, SchemaObject>();\n  const visit = (s: SchemaObject): void => {\n    for (const [k, v] of Object.entries(s.properties ?? {})) {\n      if (!props.has(k) && v) props.set(k, v);\n    }\n    for (const sub of s.allOf ?? []) visit(sub);\n    // Do NOT walk into oneOf / anyOf — those are alternatives, not\n    // simultaneously-present properties.\n  };\n  visit(schema);\n  return Object.fromEntries(props);\n}\n\nfunction getEffectiveConstPropertyValue(schema: SchemaObject, property: string): string | null {\n  const direct = getConstPropertyValue(schema, property);\n  if (direct !== null) return direct;\n  const effective = getEffectiveProperties(schema)[property];\n  if (!effective) return null;\n  if (typeof effective.const === 'string') return effective.const;\n  if (Array.isArray(effective.enum) && effective.enum.length === 1 && typeof effective.enum[0] === 'string') {\n    return effective.enum[0];\n  }\n  return null;\n}\n\n/**\n * Detect an implicit discriminator on an allOf+oneOf where every variant is an\n * object that pins the same property to a distinct const value. Unlike\n * detectConstPropertyDiscriminator (which requires $ref or title for variant\n * model names), this version derives model names from the const value itself\n * using deriveDiscriminatedVariantName — matching how extractDiscriminatedAllOfVariantModels\n * names those models.\n *\n * Walks through allOf wrappers on each variant so a oneOf branch like\n *   { allOf: [{ properties: { type: { const: 'oauth' } } }, { oneOf: […] }] }\n * still surfaces `type` as a candidate discriminator.\n *\n * Returns null when no discriminator can be reliably detected.\n */\nfunction detectAllOfVariantDiscriminator(\n  variants: SchemaObject[],\n  fallbackName: string,\n): { property: string; mapping: Record<string, string> } | null {\n  // A single const-pinned variant dispatches too: its model is built and\n  // the mapping names it, as `extractDiscriminatedAllOfVariantModels` builds\n  // a variant model exactly for a union this detection accepts.\n  if (variants.length === 0) return null;\n\n  // Find a property whose const value is present on every variant\n  // (looking through allOf wrappers on each variant).\n  const firstProps = getEffectiveProperties(variants[0] ?? {});\n  let candidateProperty: string | null = null;\n  for (const propName of Object.keys(firstProps)) {\n    if (variants.every((v) => getEffectiveConstPropertyValue(v, propName) !== null)) {\n      candidateProperty = propName;\n      break;\n    }\n  }\n  if (!candidateProperty) return null;\n\n  const mapping: Record<string, string> = {};\n  const seenModelNames = new Set<string>();\n  for (const v of variants) {\n    const value = getEffectiveConstPropertyValue(v, candidateProperty);\n    if (value === null) return null;\n    const modelName = deriveDiscriminatedVariantName(v, fallbackName);\n    // If two variants map to the same model name, the discriminator is ambiguous\n    if (seenModelNames.has(modelName)) return null;\n    seenModelNames.add(modelName);\n    mapping[value] = modelName;\n  }\n\n  return { property: candidateProperty, mapping };\n}\n\n/**\n * The component an `allOf` member names, followed through a chain of\n * references (`Hop: { $ref: Alias }`), or the member itself when it is no\n * reference; `undefined` when the chain repeats or reaches a component\n * already read on this walk (`seen`), which then declares nothing more. The\n * one reference-following every reader of a component's member shares:\n * `readComponentAllOfMember` reads the member it lands on, and `memberUnion`\n * finds the union it carries.\n */\nfunction followMemberRefs(\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  seen: Set<SchemaObject>,\n): SchemaObject | undefined {\n  let resolved = member;\n  const chain = new Set<SchemaObject>();\n  while (resolved.$ref) {\n    const segments = resolved.$ref.split('/');\n    const refName = segments[segments.length - 1];\n    if (!schemas || !refName || !Object.hasOwn(schemas, refName)) break;\n    const target = schemas[refName]!;\n    if (seen.has(target) || chain.has(target)) return undefined;\n    chain.add(target);\n    resolved = target;\n  }\n  return resolved;\n}\n\n/**\n * The union a component's `allOf` member carries, read through every wrapper\n * `readComponentAllOfMember` reads the member through — a chain of\n * references (`followMemberRefs`), then a nullable union wrapper\n * (`nullableUnionBranch`) to its one non-null variant, the two alternating\n * — and `undefined` for a member that carries none, or an `allOf` member\n * (read as a component composed with `allOf`, never as a variant axis). The\n * one way the variant builder (`extractDiscriminatedAllOfVariantModels`)\n * finds a variant axis, so a union the member reader detects as a\n * dispatcher is the union whose variant models are built, whichever wrapper\n * it sits under (workos/oagen#308 merge review: a dispatcher detected\n * through `{ oneOf: [{ oneOf: [A, B] }, { type: 'null' }] }` mapped its\n * tags to models nothing built, since the builder looked at each direct\n * member's union only).\n */\nfunction memberUnion(\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): SchemaObject[] | undefined {\n  const seen = new Set<SchemaObject>();\n  let resolved: SchemaObject | undefined = member;\n  for (;;) {\n    resolved = followMemberRefs(resolved, schemas, seen);\n    if (!resolved || resolved.allOf) return undefined;\n    const branch = nullableUnionBranch(resolved);\n    if (!branch) return unionVariantsOf(resolved);\n    if (seen.has(resolved)) return undefined;\n    seen.add(resolved);\n    resolved = branch;\n  }\n}\n\nfunction extractDiscriminatedAllOfVariantModels(\n  schema: SchemaObject,\n  fallbackName: string,\n  schemas?: Record<string, SchemaObject>,\n): Model[] {\n  const models: Model[] = [];\n  const seenNames = new Set<string>();\n\n  // Collect base-object properties + required from the allOf wrapper so each\n  // variant can be emitted as a complete, self-contained type. Schemas like\n  // `EventSchema` repeat the base fields inside every variant in the spec\n  // (so this merge is a no-op there), but `ConnectApplication`'s OAuth /\n  // M2M variants don't — without this, dispatcher consumers would get a\n  // variant that's missing the shared `id` / `name` / `object` etc.\n  // The base: every declaration the members other than the variant axis\n  // make, read exactly as `extractAllOfModel` reads them\n  // (`readComponentAllOfMember`, with the component's own `properties` and\n  // `required` first — `componentAllOfMembers` — so what the component\n  // declares beside its `allOf` is a base field every variant carries, as a\n  // member's is) and resolved by the same precedence: the first\n  // always-applying declaration; a declaration a nested union's branch makes\n  // is a fallback the base carries as optional. Names are matched by own\n  // name (`Map`, `Object.fromEntries`), so a base property named\n  // `constructor`, `toString` or `__proto__` reaches every variant.\n  const members = componentAllOfMembers(schema);\n  // The variant axis: a member carrying a `oneOf`/`anyOf` — read through a\n  // reference chain and a nullable wrapper exactly as `readComponentAllOfMember`\n  // reads it (`memberUnion`) — whose variants pin one property to distinct\n  // consts — the reading `extractAllOfModel` makes of it\n  // (`detectAllOfVariantDiscriminator`) — so a variant model exists exactly\n  // when the component's model dispatches to it. A union that is not an\n  // axis is flattened into the model and builds no variant model here\n  // (workos/oagen#359 review: it did, and a model nested under such a\n  // variant took the name of the flattened field's own model).\n  const axisVariants = new Map<SchemaObject, SchemaObject[]>();\n  for (const m of members) {\n    const variants = memberUnion(m, schemas);\n    if (variants !== undefined && detectAllOfVariantDiscriminator(variants, fallbackName) !== null) {\n      axisVariants.set(m, variants);\n    }\n  }\n  const axes = new Set(axisVariants.keys());\n  if (axes.size === 0) return models;\n  const ledger = new Map<string, PropertyDeclarations>();\n  const baseRequired = new Set<string>();\n  const seen = new Set<SchemaObject>([schema]);\n  // Shared limits every variant instance must satisfy under allOf semantics:\n  // the outer wrapper's own keywords, each base member's (through its allOf\n  // wrappers), and any written beside the `oneOf` itself — everything except\n  // the branches. They ride along with the base properties and are conjoined\n  // with each variant's own below, so on a shared keyword the stricter bound\n  // wins.\n  let baseConstraints = ownConstraints(schema);\n  for (const subSchema of members) {\n    if (axes.has(subSchema)) {\n      // The axis: its branches are handled below, its own keywords bind all\n      // of them, and its own `properties` and `required` are base fields\n      // every variant carries (read without its variants).\n      readComponentAllOfMember(fallbackName, subSchema, schemas, ledger, baseRequired, seen, false);\n      baseConstraints = combineConstraints(baseConstraints, ownConstraints(subSchema));\n      continue;\n    }\n    // Any other member, a union that is not an axis included: read as the\n    // model reads it, its variants' properties as branch-only fallbacks.\n    readComponentAllOfMember(fallbackName, subSchema, schemas, ledger, baseRequired, seen);\n    baseConstraints = combineConstraints(baseConstraints, extractConstraints(subSchema));\n  }\n  // The component's own `required` naming an inherited property only, as\n  // `readComponentAllOf` reads it for the dispatcher model.\n  for (const r of schema.required ?? []) baseRequired.add(r);\n  const baseProperties: Record<string, SchemaObject> = Object.fromEntries(\n    [...ledger.values()].map((entry) => [entry.name, declaredComponentProperty(entry)]),\n  );\n\n  for (const variants of axisVariants.values()) {\n    for (const variant of variants) {\n      // Flatten any allOf wrapper on the variant (e.g. `ConnectApplication`'s\n      // OAuth branch is `allOf: [{ properties: {…} }, { oneOf: [first-party\n      // sub-variants] }]`). The flattened object has merged properties and\n      // an inlined sub-variant `oneOf` so `extractInlineModelDeep` can pull\n      // out a complete variant model.\n      const flat = flattenVariantForExtraction(variant);\n      if (!flat.properties || (flat.type !== undefined && flat.type !== 'object')) continue;\n\n      // Merge base fields into the variant. Variant-specific properties win\n      // on name collisions because the spec may pin a base field to a more\n      // specific shape inside a variant. Built through a `Map`, so a property\n      // named `__proto__` is set rather than taken for the prototype.\n      const mergedProperties = new Map<string, SchemaObject>(Object.entries(baseProperties));\n      for (const [k, v] of Object.entries(flat.properties)) {\n        if (v) mergedProperties.set(k, v);\n      }\n      const mergedRequired = new Set<string>([...baseRequired, ...(flat.required ?? [])]);\n      // The variant's own keywords (read through its allOf wrappers, like its\n      // properties) conjoined with the base members'. They are already in the\n      // 3.1 shape, so spreading them into the rebuilt schema lets\n      // extractInlineModelDeep's constraintsEntry read them back unchanged.\n      const merged: SchemaObject = {\n        type: 'object',\n        properties: Object.fromEntries(mergedProperties),\n        required: [...mergedRequired],\n        // The variant's own flag only: the union's wrapper deprecates the\n        // dispatcher model, not the variants it dispatches to.\n        ...deprecatedEntry(variant),\n        ...combineConstraints(baseConstraints, extractConstraints(variant)),\n        // The variant's own link rides along like its keywords, so the model\n        // built from the rebuilt schema carries it; so do its own extensions.\n        ...externalDocsEntry(variant.externalDocs),\n        ...extensionsOf(variant, SCHEMA_CONSUMED_EXTENSIONS),\n      };\n\n      const variantName = deriveDiscriminatedVariantName(variant, fallbackName);\n      for (const model of extractInlineModelDeep(variantName, merged, schemas)) {\n        if (seenNames.has(model.name)) continue;\n        seenNames.add(model.name);\n        models.push(model);\n      }\n    }\n  }\n\n  return models;\n}\n\n/**\n * Flatten a oneOf variant schema into a single object-shaped schema for\n * variant-model extraction. Recursively merges `allOf` members and folds\n * any nested `oneOf` into an inline-oneOf field group whose properties are\n * the union across sub-branches (required only when present in every\n * sub-branch). Returns the schema unchanged when no flattening is needed.\n */\nfunction flattenVariantForExtraction(variant: SchemaObject): SchemaObject {\n  if (!variant.allOf) return variant;\n\n  // A `Map`, returned through `Object.fromEntries`, so a property named\n  // `__proto__` is kept as an own entry.\n  const mergedProperties = new Map<string, SchemaObject>();\n  const mergedRequired = new Set<string>();\n  const nestedOneOfs: SchemaObject[][] = [];\n\n  const collect = (s: SchemaObject): void => {\n    if (s.properties) {\n      for (const [k, v] of Object.entries(s.properties)) {\n        if (!mergedProperties.has(k) && v) mergedProperties.set(k, v);\n      }\n    }\n    if (s.required) {\n      for (const r of s.required) mergedRequired.add(r);\n    }\n    if (s.allOf) {\n      for (const sub of s.allOf) collect(sub);\n    }\n    const nested = unionVariantsOf(s);\n    if (nested) nestedOneOfs.push(nested);\n  };\n  collect(variant);\n\n  // Fold each nested oneOf into the merged shape: any field appearing in any\n  // sub-branch is included as optional (or required iff present-and-required\n  // in every sub-branch). Conflicting literal types widen to their primitive\n  // base. This handles the `is_first_party: true | false` widening on the\n  // OAuth variant's first-party sub-oneOf.\n  for (const branches of nestedOneOfs) {\n    const flatBranches = branches.map(flattenVariantForExtraction);\n    const branchKeys = new Set<string>();\n    for (const b of flatBranches) {\n      for (const k of Object.keys(b.properties ?? {})) branchKeys.add(k);\n    }\n    for (const key of branchKeys) {\n      const schemas: SchemaObject[] = [];\n      for (const b of flatBranches) {\n        const s = b.properties?.[key];\n        if (s) schemas.push(s);\n      }\n      const merged = mergeBranchPropertySchemas(schemas);\n      if (!mergedProperties.has(key)) mergedProperties.set(key, merged);\n      const inAllBranches = flatBranches.every((b) => b.properties !== undefined && Object.hasOwn(b.properties, key));\n      const requiredInAll = inAllBranches && flatBranches.every((b) => (b.required ?? []).includes(key));\n      if (requiredInAll) mergedRequired.add(key);\n    }\n  }\n\n  return {\n    type: 'object',\n    properties: Object.fromEntries(mergedProperties),\n    required: [...mergedRequired],\n  };\n}\n\n/**\n * Merge same-named property schemas from across sub-variants. If every\n * occurrence is a boolean const, widen to plain boolean; if every occurrence\n * is a distinct string const, widen to plain string. Otherwise return the\n * first occurrence — emitters that build their own widened types (e.g. the\n * Node discriminated-models module) re-derive from the raw spec. Whichever\n * way, the result carries exactly the extensions every occurrence agrees on\n * (`agreedExtensions`, the one rule for a property several declarations\n * give; workos/oagen#369 review: a widened field kept `type` and\n * `description` alone, so a shared `x-since` was lost, and the first\n * occurrence was returned with its own keys, disputed or not).\n */\nfunction mergeBranchPropertySchemas(schemas: SchemaObject[]): SchemaObject {\n  if (schemas.length === 0) return {};\n  if (schemas.length === 1) return schemas[0];\n  const extensions = agreedExtensions(schemas);\n\n  const allBoolConst = schemas.every((s) => s.type === 'boolean' && typeof s.const === 'boolean');\n  if (allBoolConst) {\n    return { type: 'boolean', description: schemas[0].description, ...extensions };\n  }\n  const allStringConst = schemas.every((s) => s.type === 'string' && typeof s.const === 'string');\n  if (allStringConst) {\n    const values = schemas.map((s) => s.const as string);\n    if (new Set(values).size === 1) return withAgreedExtensions(schemas[0], extensions);\n    return { type: 'string', description: schemas[0].description, ...extensions };\n  }\n  return withAgreedExtensions(schemas[0], extensions);\n}\n\nfunction deriveDiscriminatedVariantName(schema: SchemaObject, fallbackName: string): string {\n  // Walk through allOf wrappers so a variant of the form\n  // `{ allOf: [{ properties: { type: const: 'oauth' } }, { oneOf: […] }] }`\n  // still surfaces its discriminator const value for naming.\n  const effective = getEffectiveProperties(schema);\n  if (Object.keys(effective).length === 0) return fallbackName;\n\n  const pickConst = (name: string): string | null => {\n    const field = effective[name];\n    if (!field) return null;\n    if (typeof field.const === 'string') return field.const;\n    if (field.enum && field.enum.length === 1 && typeof field.enum[0] === 'string') {\n      return field.enum[0];\n    }\n    return null;\n  };\n\n  let constValue: string | null = null;\n  for (const preferred of ['event', 'type', 'object']) {\n    constValue = pickConst(preferred);\n    if (constValue) break;\n  }\n  if (constValue === null) {\n    for (const name of Object.keys(effective)) {\n      constValue = pickConst(name);\n      if (constValue) break;\n    }\n  }\n  if (constValue === null) return fallbackName;\n\n  const pascal = toPascalCase(constValue);\n  if (!pascal) return fallbackName;\n\n  // A single-word const like `oauth` or `m2m` is too generic to stand alone\n  // as a top-level model name — it would collide with unrelated schemas. Pair\n  // it with the parent name so the variant resolves to e.g. `ConnectApplicationOAuth`\n  // / `ConnectApplicationM2M`. Multi-word consts like `action.authentication.denied`\n  // are already specific enough on their own, matching the established\n  // EventSchema variant naming.\n  const wordCount = splitWords(constValue).length;\n  if (wordCount >= 2) return pascal;\n  if (pascal === fallbackName) return pascal;\n  if (fallbackName.startsWith(pascal)) return fallbackName;\n  if (pascal.endsWith(fallbackName)) return pascal;\n  return `${fallbackName}${pascal}`;\n}\n\n/**\n * The model for a discriminated variant's rebuilt object schema, and every\n * inline model its fields reference: the variant's own model\n * (`buildInlineModel`, its properties typed under `name`) followed by\n * whatever its properties mint, extracted by the field extractor\n * (`extractInlineModelsFromProperties`) under `name` as parent — so a\n * nested object, typed or not, nullable or not; array items and map values\n * of any shape (an inline object, an `allOf` merge, a union); every\n * `oneOf`/`anyOf` variant and its members; an `allOf` field read as\n * `readInlineAllOf` reads it; an inline enum — is materialized under exactly\n * the name `buildFieldFromSchema` typed it with, since the extractor and the\n * type builder name by the same rules. A variant's fields are built here\n * the one way every inline object's are, so typing and extraction cannot\n * disagree for any shape under a discriminated variant.\n */\nfunction extractInlineModelDeep(name: string, schema: SchemaObject, schemas?: Record<string, SchemaObject>): Model[] {\n  const nestedModels: Model[] = [];\n  extractInlineModelsFromProperties(schema, nestedModels, name, schemas);\n  return [buildInlineModel(name, schema, schemas), ...nestedModels];\n}\n\n/**\n * `elementContextName` for an optional context: with no field name there is\n * nothing to decide, and the items / values keep an undefined context.\n */\nfunction elementContext(\n  contextName: string | undefined,\n  kind: 'item' | 'value',\n  siblingProperties: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  elementSchema: SchemaObject,\n): string | undefined {\n  return contextName === undefined\n    ? undefined\n    : elementContextName(contextName, kind, siblingProperties, parentModelName, elementSchema);\n}\n\n/**\n * Every `ModelRef` built from a `$ref` — an explicit reference to a component\n * schema, as opposed to one minted for an inline object. The two kinds carry\n * the same `{ kind: 'model', name }` shape, so the identity is kept here: a\n * pass that renames an inline model repoints the references minted for it and\n * must leave an explicit reference to a same-named component as written\n * (`isComponentModelRef`). The set is keyed by object identity and every\n * pass between building and emitting mutates refs in place, so it holds.\n */\nconst componentModelRefs = new WeakSet<ModelRef>();\n\n/** Whether `ref` was built from a `$ref` to a component schema rather than minted for an inline object. */\nexport function isComponentModelRef(ref: ModelRef): boolean {\n  return componentModelRefs.has(ref);\n}\n\n/** Record `ref` as built from a `$ref` to a component: for a copy of a marked reference (`cloneTypeRef`), which a structural clone would leave unmarked. */\nexport function markComponentModelRef(ref: ModelRef): void {\n  componentModelRefs.add(ref);\n}\n\nexport function schemaToTypeRef(\n  schema: SchemaObject,\n  contextName?: string,\n  parentModelName?: string,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n  // The inline names an enclosing field's siblings mint, handed down to the\n  // field's array items and map values so a union among them steps around a\n  // sibling's model like a union at field level (`reservedNamesFor`).\n  reservedNames?: ReadonlySet<string>,\n): TypeRef {\n  // Handle $ref → ModelRef or EnumRef.\n  // A `$ref` to a top-level component schema needs to preserve whether the\n  // target is a model or an enum, because emitters route imports differently\n  // for the two kinds (e.g. com.example.models.X vs com.example.types.X). The\n  // set of enum names is precomputed by extractSchemas() in a first pass so\n  // it's available even when called recursively for nested $refs.\n  if (schema.$ref) {\n    const segments = schema.$ref.split('/');\n    const rawName = segments[segments.length - 1];\n    // An array component is no model: the reference is the array it\n    // declares, its items typed under the component's name exactly as the\n    // component pass materializes them (`arrayComponentTypeRef`). Looked up\n    // by the key the `$ref` names, before any name-based test: `Notes` is\n    // the array whatever another key resolving to `Note` is.\n    const arrayAlias = arrayComponentTypeRef(rawName);\n    if (arrayAlias) return arrayAlias;\n    const resolved = resolveSchemaName(rawName);\n    if (activeEnumSchemaNames.has(resolved)) {\n      const enumRef: TypeRef = { kind: 'enum', name: resolved };\n      // Carry the component's own nullability through the reference so\n      // `field: { $ref: NullableEnum }` has the same shape as the inline\n      // `oneOf: [{ $ref }, { type: 'null' }]` form.\n      return activeNullableEnumSchemaNames.has(resolved) ? { kind: 'nullable', inner: enumRef } : enumRef;\n    }\n    // Likewise a named union with a `null` variant: the variant is not a\n    // member of the model, so the reference carries the nullability. The\n    // model reference itself is recorded as a component's (`componentModelRefs`)\n    // whether or not it is wrapped.\n    const modelRef: ModelRef = { kind: 'model', name: resolved };\n    componentModelRefs.add(modelRef);\n    return activeNullableUnionSchemaNames.has(resolved) ? { kind: 'nullable', inner: modelRef } : modelRef;\n  }\n\n  // Handle OAS 3.1 nullable type arrays: type: [string, null]\n  if (Array.isArray(schema.type)) {\n    const nonNullTypes = schema.type.filter((t: string) => t !== 'null');\n    // type: ['null'] — only null, no real type\n    if (nonNullTypes.length === 0) {\n      return { kind: 'nullable', inner: { kind: 'primitive', type: 'unknown' } };\n    }\n    // Keep `parentModelName` through the unwrap so an inline object, map\n    // value, or enum under a nullable field is qualified exactly like its\n    // non-nullable twin — the inline-model extractor names it that way.\n    if (schema.type.includes('null') && nonNullTypes.length === 1) {\n      return asNullable(\n        schemaToTypeRef(\n          { ...schema, type: nonNullTypes[0], nullable: false },\n          contextName,\n          parentModelName,\n          siblingProperties,\n          reservedNames,\n        ),\n      );\n    }\n    // Multiple non-null types → union\n    if (nonNullTypes.length > 1) {\n      const variants = nonNullTypes.map((t: string) =>\n        schemaToTypeRef({ ...schema, type: t }, contextName, parentModelName, siblingProperties, reservedNames),\n      );\n      const ref: TypeRef = { kind: 'union', variants };\n      if (schema.type.includes('null')) {\n        return { kind: 'nullable', inner: ref };\n      }\n      return ref;\n    }\n  }\n\n  // Handle OAS 3.0 nullable flag\n  if (schema.nullable && schema.type) {\n    return asNullable(\n      schemaToTypeRef({ ...schema, nullable: false }, contextName, parentModelName, siblingProperties, reservedNames),\n    );\n  }\n\n  // From here on the nullable wrappers are gone. `properties` written beside\n  // a typing `allOf`/`oneOf`/`anyOf` are folded into it (the extractors\n  // dispatch on the same fold, through `unwrapNullableSchema`), the variants\n  // that cannot take them reported, and then one classification decides\n  // which keyword types the schema — the same one the inline-model\n  // extractors dispatch on, so the models they build are the ones referenced.\n  // A schema no branch below types is `unknown` — decided by\n  // `typesAsUnknown`, the one answer a reader that must know before typing\n  // asks (`bodyTypesAsUnknown`, for the primary response) — with a warning for a\n  // shape the parser does not read; an empty `{}` describes nothing on\n  // purpose and is not reported.\n  if (typesAsUnknown(schema)) {\n    if (contextName && !describesNothing(schema)) {\n      console.warn(`[oagen] Warning: Unknown schema shape treated as unknown (context: ${contextName})`);\n    }\n    return { kind: 'primitive', type: 'unknown' };\n  }\n\n  warnOnUncarriedProperties(schema, contextName, parentModelName);\n  schema = foldSiblingProperties(schema);\n  const inlineKind = classifyInlineSchema(schema);\n\n  // Handle allOf, read the one way every site reads it (`readInlineAllOf`):\n  // a merged model — a `$ref` member augmented by an inline object member,\n  // or inline members one of which declares properties, a `oneOf`/`anyOf`\n  // member's inline object variants included — which `materializeMergedAllOf`\n  // builds under this very name; a lone member unwrapped; or a plain\n  // reference to the first `$ref` member.\n  if (inlineKind === 'allOf' && schema.allOf) {\n    const reading = readInlineAllOf(schema.allOf, schema);\n    if (reading === 'merged') {\n      const baseName = toPascalCase(contextName ?? 'UnknownModel');\n      return { kind: 'model', name: qualifyInlineModelName(baseName, parentModelName) };\n    }\n    if (reading === 'reference') {\n      const refItem = schema.allOf.find((s: SchemaObject) => s.$ref);\n      // `'reference'` is only read with a `$ref` member among the members an\n      // `allOfTypesSchema` admits, so one is found here.\n      if (refItem) return schemaToTypeRef(refItem, contextName, parentModelName);\n    } else {\n      // A single member, unwrapped. The wrapper is the schema the document\n      // wrote, so its documentation rides onto the member — an inline enum\n      // lifted from it carries the wrapper's `description` and link\n      // (`withWrapperDocs`), and a model built from it the wrapper's link\n      // (`unwrappedAllOfMember`).\n      return schemaToTypeRef(\n        withWrapperDocs(schema.allOf[0], schema),\n        contextName,\n        parentModelName,\n        siblingProperties,\n        reservedNames,\n      );\n    }\n    // Unreachable: `allOfTypesSchema` admits only the three readings above.\n    // An `allOf` of bare limits is classified from the schema's own keywords.\n  }\n\n  // Handle oneOf / anyOf → Union or Nullable\n  // Valid OAS 3.1: properties can have { oneOf: [{ type: object }, { type: 'null' }] }\n  // without a wrapping `type` field.\n  if (inlineKind === 'union') {\n    const compositionKind: 'oneOf' | 'anyOf' = schema.oneOf ? 'oneOf' : 'anyOf';\n    const rawVariants: SchemaObject[] = schema.oneOf ?? schema.anyOf ?? [];\n\n    // Check for nullable pattern: oneOf: [realType, { type: 'null' }]\n    const nullVariant = rawVariants.find(isNullVariantSchema);\n    const nonNullVariants = rawVariants.filter((v) => v !== nullVariant);\n\n    // Collapse an oneOf/anyOf whose non-null variants are all string-const\n    // schemas into a single enum. This turns patterns like\n    //   provider: { oneOf: [{ const: \"AppleOAuth\" }, { const: \"GitHubOAuth\" }, ...] }\n    // into a proper enum type with one member per variant instead of a\n    // structurally-opaque union of literal refs. Each member keeps its\n    // variant's `description` and `deprecated` (`constUnionEnumMembers`), the\n    // way the same `oneOf` under `components.schemas` does (`extractEnum`).\n    // An `enum:` list beside the union restricts the members and `null`\n    // alike, through the two helpers the component path reads\n    // (`constUnionEnumMembers`, `enumListAdmitsNull`), whatever it leaves:\n    // one member is an enum of that member, none an enum with no members —\n    // the component's answers — never the union of every const the list\n    // forbade, nor the nullable literal the single-variant unwrap below would\n    // make of `oneOf: [a, null]` when the list forbids `null`; so this is\n    // decided first. Without a list, a union of fewer than two consts keeps\n    // the shape the branches below give it (a lone const beside\n    // `type: 'null'` is a nullable literal).\n    // Whether this union is such an enum is the one decision the predictor\n    // that reserves enum names before typing reads too (`inlineEnumSpelling`).\n    const constUnion = inlineEnumSpelling(schema);\n    if (constUnion?.spelling === 'const-union') {\n      const enumRef = buildSyntheticEnumRef(\n        constUnion.members,\n        contextName,\n        parentModelName,\n        schema.externalDocs,\n        schema.description,\n        extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n      );\n      // An `enum:` list beside the union that leaves `null` out forbids it,\n      // whatever the `type: 'null'` variant says (`enumListAdmitsNull`).\n      return nullVariant && enumListAdmitsNull(schema) ? { kind: 'nullable', inner: enumRef } : enumRef;\n    }\n\n    if (nullVariant && nonNullVariants.length === 1) {\n      // Nullable single type — unwrap as nullable. `asNullable` keeps a\n      // `$ref` to an already-nullable enum component from double-wrapping.\n      // The wrapper's `description` and link ride onto the branch\n      // (`withWrapperDocs`), so an inline enum under a nullable wrapper lifts\n      // with the wrapper's text and link; the model the extractor builds from\n      // the same branch takes the wrapper's link (`unwrapNullableField`).\n      return asNullable(\n        schemaToTypeRef(\n          withWrapperDocs(nonNullVariants[0], schema),\n          contextName,\n          parentModelName,\n          siblingProperties,\n          reservedNames,\n        ),\n      );\n    }\n\n    // The inline object variants' model names, decided once for this TypeRef\n    // and every extractor (`nameInlineVariants`): variant 0's bare qualified\n    // field name, a const prefix, a title, a distinguishing property or a\n    // counter — or, for a `oneOf` whose every variant is titled and pins a\n    // const (3. below), the title itself — never a name a sibling property\n    // mints. Computed first because the derived discriminator mappings below\n    // are read from it, so a mapping can only point at a model that exists.\n    const inlineVariantNames = nameInlineObjectVariants(\n      schema,\n      contextName,\n      parentModelName,\n      siblingProperties,\n      reservedNames,\n    );\n\n    // Resolve the discriminator. Four sources, in order:\n    //   1. Explicit `discriminator:` with explicit `mapping:` — trust the spec.\n    //   2. Explicit `discriminator:` with no `mapping:` — pair each variant's\n    //      const value on the property with its inline model name\n    //      (`deriveInlineVariantMapping`). This covers `ApiKey.owner`-shaped\n    //      schemas where the spec uses `discriminator: { propertyName: type }`\n    //      but lists inline anonymous `oneOf` variants instead of `$ref` links.\n    //   3. No explicit discriminator, but every variant carries a `$ref` or a\n    //      `title` and pins the same const property\n    //      (`titleMappedDiscriminatorProperty`): the mapping names a `$ref`\n    //      variant by its component and an inline variant by the name\n    //      `nameInlineVariants` gave it — its title (`Circle`, `Square`)\n    //      unless that is taken — so the extracted model and the mapping agree.\n    //   4. Otherwise, when every inline variant pins the same const property\n    //      with distinct values (`deriveConstNamingDiscriminator`), the same\n    //      value → inline model name pairing as 2. This covers\n    //      `ApiKeyCreatedData.owner`-shaped schemas (oneOf with inline\n    //      const-discriminating variants but no `discriminator:` keyword).\n    let resolvedDiscriminator: { property: string; mapping: Record<string, string> } | undefined;\n    if (schema.discriminator) {\n      const property = schema.discriminator.propertyName;\n      const explicitMapping = schema.discriminator.mapping ?? {};\n      let mapping: Record<string, string> = Object.fromEntries(\n        Object.entries(explicitMapping).map(([k, v]) => [k, v.replace(/^#\\/components\\/schemas\\//, '')]),\n      );\n      if (Object.keys(mapping).length === 0) {\n        const inlineMapping = deriveInlineVariantMapping(nonNullVariants, property, contextName, inlineVariantNames);\n        if (inlineMapping) mapping = inlineMapping;\n      }\n      resolvedDiscriminator = { property, mapping };\n    } else if (compositionKind === 'oneOf') {\n      const titleProperty = titleMappedDiscriminatorProperty(nonNullVariants);\n      if (titleProperty) {\n        const mapping: Record<string, string> = {};\n        for (const v of nonNullVariants) {\n          const value = getConstPropertyValue(v, titleProperty);\n          const mappedName = inlineVariantNames.get(v) ?? resolveVariantModelName(v);\n          if (value !== null && mappedName !== null) mapping[value] = mappedName;\n        }\n        resolvedDiscriminator = { property: titleProperty, mapping };\n      } else {\n        const namingDisc = deriveConstNamingDiscriminator(nonNullVariants);\n        if (namingDisc) {\n          const inlineMapping = deriveInlineVariantMapping(\n            nonNullVariants,\n            namingDisc.property,\n            contextName,\n            inlineVariantNames,\n          );\n          if (inlineMapping) {\n            resolvedDiscriminator = { property: namingDisc.property, mapping: inlineMapping };\n          }\n        }\n      }\n    }\n\n    // Build variants. An inline object variant is referenced by the name its\n    // extracted model carries (`inlineVariantNames`); a discriminator mapping\n    // entry substitutes for it only when the spec's own `mapping:` (1.) names\n    // the variant, since the derived mappings (2.–4.) are read from the same\n    // names. Falling back to `schemaToTypeRef` instead would hand every\n    // inline variant the same parent-derived name (e.g. `ApiKeyOwner`),\n    // collapsing the union onto one repeated model ref while the extractor\n    // emits `ApiKeyOwner`, `UserApiKeyOwner`, ... for them.\n    // The named ref replaces only the `object` member of what `schemaToTypeRef`\n    // would build for the variant: a nullable variant (`['object', 'null']`,\n    // OAS 3.0 `nullable: true`) keeps its wrapper, and a multi-type variant\n    // (`['object', 'string']`) keeps its other alternatives in a union — see\n    // `inlineVariantTypeRef`. The extractor emits the model under the same\n    // name in every case, and a multi-type variant's other members are named\n    // from that model, not from the mapping, so their items resolve.\n    const variants: TypeRef[] = [];\n    // Every other variant that mints a name — an array or map, a nested\n    // union, a nullable wrapper around an object, an `allOf`, an inline enum\n    // — is typed under the context `nonObjectVariantContexts` gives it, so\n    // the models and enums it mints never share a name with an object\n    // variant of the same union, which keeps the field's own name, nor with\n    // another such variant's. The extractors re-enter with the same contexts.\n    const variantContexts = nonObjectVariantContexts(\n      contextName,\n      rawVariants,\n      siblingProperties,\n      parentModelName,\n      inlineVariantNames,\n      reservedNames,\n    );\n    for (const v of rawVariants) {\n      if (v === nullVariant) continue;\n      const inlineName = inlineVariantNames.get(v);\n      if (inlineName) {\n        const mappedName = resolvedDiscriminator ? mapVariantToDiscriminatorEntry(v, resolvedDiscriminator) : null;\n        variants.push(inlineVariantTypeRef(v, inlineName, mappedName ?? inlineName));\n      } else {\n        const entry = variantContexts.get(v);\n        variants.push(\n          entry\n            ? schemaToTypeRef(v, entry.context, parentModelName, undefined, entry.reserved)\n            : schemaToTypeRef(v, contextName, parentModelName),\n        );\n      }\n    }\n    const hasNull = !!nullVariant;\n\n    const union: TypeRef = {\n      kind: 'union',\n      variants,\n      compositionKind,\n      ...(resolvedDiscriminator ? { discriminator: resolvedDiscriminator } : {}),\n    };\n    return hasNull ? { kind: 'nullable', inner: union } : union;\n  }\n\n  // Handle const → LiteralType (supports string, number, boolean)\n  if (inlineKind === 'const') {\n    if (typeof schema.const === 'string' || typeof schema.const === 'number' || typeof schema.const === 'boolean') {\n      return { kind: 'literal', value: schema.const };\n    }\n    // null const → nullable unknown\n    if (schema.const === null) {\n      return { kind: 'nullable', inner: { kind: 'primitive', type: 'unknown' } };\n    }\n    // const of object/array → map or array with unknown values\n    if (typeof schema.const === 'object') {\n      if (Array.isArray(schema.const)) {\n        return { kind: 'array', items: { kind: 'primitive', type: 'unknown' } };\n      }\n      return { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } };\n    }\n  }\n  // A `null` member of an inline `enum:` marks nullability, not a value.\n  // Strip it before deciding literal-vs-enum, and wrap the result so a\n  // bare `type: 'string', enum: ['a', null]` is nullable even without a\n  // `type: [..., 'null']` array (the array branch above already wrapped\n  // us when present; `asNullable` keeps that from doubling up).\n  const enumValues = nonNullEnumValues(schema.enum);\n  const enumAdmitsNull = schema.enum !== undefined && enumValues.length !== schema.enum.length;\n  if (inlineKind === 'enum' && enumValues.length === 1) {\n    const v = enumValues[0];\n    const literal: TypeRef = { kind: 'literal', value: typeof v === 'number' ? v : String(v) };\n    return enumAdmitsNull ? asNullable(literal) : literal;\n  }\n\n  // Handle enum — the `enum-list` spelling of the one decision the predictor\n  // that reserves enum names before typing reads too (`inlineEnumSpelling`);\n  // the single-member list was returned as a literal above.\n  if (inlineEnumSpelling(schema)?.spelling === 'enum-list') {\n    // Named by the one rule every inline enum follows (`inlineEnumName`):\n    // qualified by the parent with its list-item markers stripped, no\n    // redundant prefix, the project's `schemaNameTransform` applied. The\n    // schema's `description`, link and extensions and each value's\n    // `x-enum-descriptions` / `x-enumDescriptions` entry are recorded against\n    // the ref so the lifted `Enum` carries them (`collectInlineEnumFromRef`);\n    // the nullable unwraps above spread the schema, so a wrapped enum's text,\n    // link and keys reach here too.\n    const enumRef = inlineEnumRef(\n      inlineEnumName(contextName, parentModelName),\n      enumListMembers(schema) ?? [],\n      schema.externalDocs,\n      schema.description,\n      extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n    );\n    return enumAdmitsNull ? asNullable(enumRef) : enumRef;\n  }\n\n  // Handle array — pass parentModelName through to qualify inline items. The\n  // items' context is the field itself, or `<field>_item` when a sibling\n  // property would take the singular name (`elementContextName`), so an\n  // inline object item is `<Parent><Field>` or `<Parent><Field>Item`. The\n  // items get no sibling set of their own (they are not a property), but a\n  // union among them must still step around the models the field's siblings\n  // mint, so that set is handed down (`reservedNamesFor`), exactly as the\n  // extractor passes it into its items re-entry.\n  if (inlineKind === 'array' && schema.items) {\n    return {\n      kind: 'array',\n      items: schemaToTypeRef(\n        schema.items,\n        elementContext(contextName, 'item', siblingProperties, parentModelName, schema.items),\n        parentModelName,\n        undefined,\n        reservedNamesFor(contextName, siblingProperties, parentModelName, reservedNames),\n      ),\n    };\n  }\n\n  // Handle object → ModelRef (if it has properties, it's a named model reference,\n  // with `type: 'object'`, no `type`, or a type list naming `object`).\n  // When additionalProperties is also present, we still return a ModelRef so the\n  // named properties are preserved. The extractModel path will pick up the extra\n  // properties as a catch-all map field named `additionalProperties`.\n  if (inlineKind === 'object') {\n    const baseName = toPascalCase(contextName ?? 'UnknownModel');\n    return {\n      kind: 'model',\n      name: qualifyInlineModelName(baseName, parentModelName),\n    };\n  }\n\n  // Handle freeform object with additionalProperties or patternProperties → Map<string, T>\n  // The value schema is typed with the field's own `contextName` and\n  // `parentModelName`, exactly like array items, so an inline object value is\n  // referenced as `${Parent}${SingularField}` (`layers` on\n  // `CreateDrawingRequest` → `CreateDrawingRequestLayer`) and the inline-model\n  // extractor (`extractInlineModelsFromProperties`) emits a model of that name.\n  // When a sibling property would take that singular name the values use\n  // `<field>_value` instead (`<Parent><Field>Value`, see `elementContextName`).\n  if (inlineKind === 'map') {\n    // `mapValueSchema` picks the value schema in this branch's precedence: a\n    // non-empty `additionalProperties` object, else the first\n    // `patternProperties` entry; `additionalProperties: {}` or `true` means\n    // \"any value\" and stays unknown.\n    let valueType: TypeRef = { kind: 'primitive', type: 'unknown' };\n    const valueSchema = mapValueSchema(schema);\n    if (valueSchema) {\n      const valueContext = elementContext(contextName, 'value', siblingProperties, parentModelName, valueSchema);\n      // Like array items: the field's sibling reservations reach the values.\n      valueType = schemaToTypeRef(\n        valueSchema,\n        valueContext,\n        parentModelName,\n        undefined,\n        reservedNamesFor(contextName, siblingProperties, parentModelName, reservedNames),\n      );\n    }\n    return {\n      kind: 'map',\n      valueType,\n    };\n  }\n\n  // Handle primitives\n  const typeStr = Array.isArray(schema.type) ? schema.type[0] : schema.type;\n  if (typeStr && PRIMITIVE_TYPES[typeStr]) {\n    return {\n      kind: 'primitive',\n      type: PRIMITIVE_TYPES[typeStr],\n      ...(schema.format ? { format: schema.format } : {}),\n    };\n  }\n\n  // Unreachable: every shape no branch above types was answered at the top\n  // (`typesAsUnknown` holds exactly for those).\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/** The `type` keywords `schemaToTypeRef` reads as a primitive, and the primitive each becomes. */\nconst PRIMITIVE_TYPES: Record<string, 'string' | 'integer' | 'number' | 'boolean'> = {\n  string: 'string',\n  integer: 'integer',\n  number: 'number',\n  boolean: 'boolean',\n};\n\n/** An empty schema — `{}`, or one with annotations only: none of the keywords that type a schema. */\nfunction describesNothing(schema: SchemaObject): boolean {\n  return (\n    !schema.type &&\n    !schema.$ref &&\n    !schema.oneOf &&\n    !schema.anyOf &&\n    !schema.allOf &&\n    !schema.enum &&\n    !schema.properties &&\n    !schema.items\n  );\n}\n\n/**\n * Whether `schemaToTypeRef` types `schema` as the bare `unknown` primitive,\n * decided without typing it — the one answer, which `schemaToTypeRef`\n * itself returns on, so a reader that must know before a body is typed\n * (`bodyTypesAsUnknown`, choosing the primary response, which asks here\n * only where classification ends on `schemaToTypeRef`) never disagrees\n * with the type it then gets. It holds for a schema no branch of `schemaToTypeRef`\n * types: no `$ref`; no type list except one naming a single type without\n * `null` (an empty list is `nullable<unknown>`, `null` beside one type is\n * nullable, several types are a union); no `nullable: true` beside a\n * `type`; then, once sibling properties are folded into a typing\n * composition (`foldSiblingProperties`), a classification of `other`\n * (`classifyInlineSchema`: no composition, union, `const`, `enum`, array,\n * object or map) with no primitive `type` — `{}`, `{ nullable: true }`, a\n * `type` no rule knows, `type: 'array'` without `items`, a bare\n * `additionalProperties` without `type: 'object'` — or a lone `allOf`\n * member read as the schema itself (`readInlineAllOf`: `'unwrapped'`)\n * that is such a schema. Warns about nothing.\n */\nexport function typesAsUnknown(schema: SchemaObject): boolean {\n  if (schema.$ref) return false;\n  if (Array.isArray(schema.type)) {\n    const nonNullTypes = schema.type.filter((t: string) => t !== 'null');\n    if (nonNullTypes.length !== 1 || schema.type.includes('null')) return false;\n  }\n  if (schema.nullable && schema.type) return false;\n  const folded = foldSiblingProperties(schema);\n  const kind = classifyInlineSchema(folded);\n  if (kind === 'allOf' && folded.allOf) {\n    return readInlineAllOf(folded.allOf, folded) === 'unwrapped' && typesAsUnknown(folded.allOf[0]);\n  }\n  if (kind !== 'other') return false;\n  const typeStr = Array.isArray(folded.type) ? folded.type[0] : folded.type;\n  return !(typeStr && PRIMITIVE_TYPES[typeStr]);\n}\n\nimport {\n  buildInlineModel,\n  collectProperties,\n  declareProperty,\n  declaresInlineProperties,\n  elementContextName,\n  extractInlineModelsFromProperties,\n  extractInlineModelsFromSchemas,\n  firstFreeElementContext,\n  isContestedTitle,\n  mapValueSchema,\n  markContestedTitles,\n  readInlineAllOf,\n  unwrappedAllOfMember,\n  agreedExtensions,\n  withAgreedExtensions,\n  type MintedInlineName,\n  mintedInlineNameEntries,\n  mintedInlineNames,\n  modelFingerprint,\n  type PropertyDeclarations,\n  qualifyInlineModelName,\n  recordLiftedFieldModel,\n  reservedInlineNames,\n  resetInheritedModelRefs,\n  schemaShapeKey,\n} from './inline-models.js';\n\nexport { qualifyInlineModelName, extractInlineModelsFromSchemas } from './inline-models.js';\n","import type {\n  TypeRef,\n  Parameter,\n  Model,\n  PaginationMeta,\n  PaginationEndOfIteration,\n  PaginationStrategy,\n} from '../ir/types.js';\nimport type { PaginationHint } from '../ir/operation-hints.js';\nimport type { SchemaObject } from './schemas.js';\nimport { classifyInlineSchema, resolveComponentSchemaRef, unwrapNullableSchema } from './schemas.js';\nimport { toSnakeCase } from '../utils/naming.js';\nimport { combineDeclarations, readInlineAllOf } from './inline-models.js';\n\nconst CURSOR_PARAMS = ['cursor', 'after', 'before', 'starting_after', 'ending_before', 'page_token', 'next_token'];\n\nconst OFFSET_PARAMS = ['offset', 'skip'];\nconst PAGE_PARAMS = ['page', 'page_number', 'page_num'];\nconst LIMIT_PARAMS = ['limit', 'page_size', 'per_page', 'size', 'count'];\n\n/**\n * Detect if an operation uses pagination and return structured metadata\n * for auto-paging iterator generation.\n *\n * Recognizes three strategies from the query parameter names, in this order:\n * 1. **Cursor-based**: a cursor-like parameter (`cursor`, `after`, …)\n * 2. **Offset-based**: an item offset (`offset`, `skip`) plus a limit-like parameter\n * 3. **Page-number**: a page number (`page`, `page_number`, `page_num`) plus a\n *    limit-like parameter — the iterator advances it by one per request, not\n *    by the number of items received, starting at `pageStart`\n *\n * An offset or page parameter without a page-size parameter is not treated as\n * pagination. Returns null if no pattern is detected — and then no iterator\n * is built from the query parameters: an iterator is driven only by a\n * parameter the operation declares, never by one guessed from the response\n * (`describeUndetectedPaging` says what was missing).\n */\nexport function detectPagination(\n  response: TypeRef,\n  queryParams: Parameter[],\n  dataPath?: string,\n  options: { pageStartOf?: PageStartResolver } = {},\n): PaginationMeta | null {\n  // Try cursor-based first (preferred). Scan in CURSOR_PARAMS priority order\n  // rather than queryParams order so that an endpoint exposing both `before`\n  // and `after` reports `after` (forward iteration) — matches the wire\n  // convention where `after` advances through pages.\n  const cursorParam = CURSOR_PARAMS.map((name) => queryParams.find((p) => p.name === name)).find(\n    (p): p is Parameter => p !== undefined,\n  );\n\n  if (cursorParam) {\n    return {\n      strategy: 'cursor',\n      param: cursorParam.name,\n      dataPath: dataPath,\n      itemType: paginatedItemType(response),\n    };\n  }\n\n  // Offset and page-number pagination both need a page-size parameter.\n  const limitParam = queryParams.find((p) => LIMIT_PARAMS.includes(p.name));\n  if (!limitParam) return null;\n\n  const itemType = paginatedItemType(response);\n\n  const offsetParam = queryParams.find((p) => OFFSET_PARAMS.includes(p.name));\n  if (offsetParam) {\n    return {\n      strategy: 'offset',\n      param: offsetParam.name,\n      limitParam: limitParam.name,\n      dataPath: dataPath,\n      itemType: paginatedItemType(response),\n    };\n  }\n\n  const pageParam = queryParams.find((p) => PAGE_PARAMS.includes(p.name));\n  if (pageParam) {\n    return {\n      strategy: 'page',\n      param: pageParam.name,\n      limitParam: limitParam.name,\n      pageStart: (options.pageStartOf ?? derivePageStart)(pageParam),\n      dataPath: dataPath,\n      itemType,\n    };\n  }\n\n  return null;\n}\n\n/**\n * Why `detectPagination` finds no strategy in `queryParams`, for the warning\n * on an operation whose list envelope nothing pages: the recognized\n * parameters it declares and what is missing beside them — an offset or page\n * parameter without a page-size one, a page-size one on its own, or none of\n * the names at all. Meaningful only when `detectPagination` returned null,\n * so a cursor parameter, which alone makes an iterator, is never among the\n * declared ones.\n */\nexport function describeUndetectedPaging(queryParams: Parameter[]): string {\n  const declared = (names: readonly string[]): string[] =>\n    queryParams.filter((p) => names.includes(p.name)).map((p) => `\"${p.name}\"`);\n  // `\"page\" is` / `\"offset\" and \"page\" are` / `\"a\", \"b\" and \"c\" are`.\n  const listed = (names: string[]): string =>\n    names.length === 1 ? `${names[0]} is` : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]} are`;\n  const selectors = [...declared(OFFSET_PARAMS), ...declared(PAGE_PARAMS)];\n  if (selectors.length > 0) {\n    return `${listed(selectors)} declared without a page-size parameter: ${LIMIT_PARAMS.join(', ')}`;\n  }\n  const sizes = declared(LIMIT_PARAMS);\n  if (sizes.length > 0) return `${listed(sizes)} declared without a cursor, offset or page parameter`;\n  return 'no cursor, offset or page query parameter is declared';\n}\n\n/** Decides the first page number for a page parameter; see `derivePageStart`. */\nexport type PageStartResolver = (param: Parameter | undefined) => number;\n\n/**\n * The first page number an API expects: the page parameter's `default`, else\n * its `minimum`, else 1. Only a non-negative integer counts — a `default` of\n * `\"1\"` or `1.5` is not a page number, so the next source is tried.\n *\n * `schema` is the parameter's schema as written. The IR parameter carries a\n * `default`/`minimum` declared inline or on a bare `$ref` target, but not one\n * behind `allOf: [{ $ref }]` or a nullable wrapper; those are read from the\n * schema through `resolveSchemaKeyword`, so a component declaring `default:\n * 0` still starts the iterator at page 0.\n */\nexport function derivePageStart(\n  param: Parameter | undefined,\n  schema?: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): number {\n  const candidates = [\n    param?.default,\n    schema && resolveSchemaKeyword(schema, 'default', componentSchemas),\n    param?.constraints?.minimum,\n    schema && resolveSchemaKeyword(schema, 'minimum', componentSchemas),\n  ];\n  for (const candidate of candidates) {\n    if (typeof candidate === 'number' && Number.isInteger(candidate) && candidate >= 0) return candidate;\n  }\n  return 1;\n}\n\n/**\n * A keyword's value on a schema or on what it is composed of: the schema's\n * own value, else the component its `$ref` names, else its `allOf` members in\n * declaration order (the first that declares it wins), else the single\n * non-null variant of a nullable `oneOf`/`anyOf`. `undefined` when no level\n * declares it.\n */\nexport function resolveSchemaKeyword(\n  schema: SchemaObject,\n  keyword: 'default' | 'minimum',\n  componentSchemas?: Record<string, SchemaObject>,\n  seen: Set<string> = new Set(),\n): unknown {\n  if (schema[keyword] !== undefined) return schema[keyword];\n  if (schema.$ref) {\n    if (seen.has(schema.$ref)) return undefined;\n    seen.add(schema.$ref);\n    const resolved = resolveComponentSchemaRef(schema, componentSchemas);\n    return resolved ? resolveSchemaKeyword(resolved, keyword, componentSchemas, seen) : undefined;\n  }\n  for (const member of schema.allOf ?? []) {\n    const value = resolveSchemaKeyword(member, keyword, componentSchemas, seen);\n    if (value !== undefined) return value;\n  }\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (variants) {\n    const nonNull = variants.filter((variant) => !isNullSchema(variant));\n    if (nonNull.length === 1) return resolveSchemaKeyword(nonNull[0], keyword, componentSchemas, seen);\n  }\n  return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// End of iteration — the envelope field that says the list is exhausted\n// ---------------------------------------------------------------------------\n\n/** Boolean companions that are `false` on the last page. */\nexport const HAS_MORE_FIELDS: readonly string[] = [\n  'has_more',\n  'hasMore',\n  'has_next',\n  'hasNext',\n  'has_next_page',\n  'hasNextPage',\n];\n/** Integer companions counting the pages. */\nexport const TOTAL_PAGES_FIELDS: readonly string[] = ['total_pages', 'totalPages', 'page_count', 'pageCount'];\n/** Integer companions counting the items. */\nexport const TOTAL_COUNT_FIELDS: readonly string[] = [\n  'total',\n  'total_count',\n  'totalCount',\n  'total_items',\n  'totalItems',\n  'total_results',\n  'totalResults',\n];\n/**\n * Every companion name that can end an iteration. List-envelope detection\n * treats a companion with one of these names as pagination metadata, and\n * `detectEndOfIteration` reads it, so the two can never disagree about which\n * envelopes carry a stop field.\n */\nexport const END_OF_ITERATION_FIELDS: readonly string[] = [\n  ...HAS_MORE_FIELDS,\n  ...TOTAL_PAGES_FIELDS,\n  ...TOTAL_COUNT_FIELDS,\n];\nconst END_KIND_PRIORITY: ReadonlyArray<PaginationEndOfIteration['kind']> = ['hasMore', 'totalPages', 'totalCount'];\n\n/**\n * Substrings that mark an envelope companion as pagination metadata (`meta`,\n * `pagination`, `page_info`, `cursor`, ...), written in snake_case: the\n * spelling `looksLikePaginationMetadata` matches a companion's name in,\n * whatever case or separators the document uses. List-envelope detection\n * reads them to recognize an envelope, and `detectEndOfIteration` reads them\n * to decide which object companions to look inside for a stop field.\n */\nexport const PAGINATION_METADATA_PATTERNS: readonly string[] = [\n  'meta',\n  'metadata',\n  'pagination',\n  'cursor',\n  'has_more',\n  'page_info',\n  'total',\n  'next_page',\n  'previous_page',\n  'offset',\n];\n\n/**\n * Whether a companion's name says it carries pagination metadata: its\n * snake_case spelling (`toSnakeCase`, which splits the name into words as\n * `toPascalCase` does) contains one of `PAGINATION_METADATA_PATTERNS`. The\n * name is read by its words, so case and separators do not matter —\n * `page_info`, `pageInfo`, `PageInfo` and `page-info` are all `page_info` —\n * while a pattern never straddles a word boundary: `nameTag` is `name_tag`,\n * which does not contain `meta`. The one recognizer for list-envelope\n * detection and the nested stop-field scan, so the two cannot disagree\n * about which companions are pagination metadata.\n */\nexport function looksLikePaginationMetadata(name: string): boolean {\n  const spelled = toSnakeCase(name);\n  return PAGINATION_METADATA_PATTERNS.some((pattern) => spelled.includes(pattern));\n}\n\n/**\n * Find the envelope field that ends an iteration, when the envelope declares\n * an obvious one. `properties` are the envelope's merged properties and\n * `dataPath` names the data array among them.\n *\n * The fields beside the array are considered first: when the path is\n * nested, the other properties of the object the array sits in, under\n * whatever name that object has (`result.total_pages` beside\n * `result.items`, `data.page.has_more` beside `data.page.items`), the\n * parent reached exactly as the path itself is resolved\n * (`resolveSchemaPath` from the merged properties), so one behind a `$ref`,\n * an `allOf` or a nullable wrapper is read as the walk reads it. Then the\n * top-level fields, then the fields one level down inside each top-level\n * object companion whose name says it is pagination metadata\n * (`looksLikePaginationMetadata`: `meta`, `pagination`, `page_info`, ..., in\n * any spelling — `pageInfo` and `PageInfo` as much as `page_info`; an\n * inline object, a `$ref` to a component, an `allOf` of those, or a nullable\n * wrapper around one), so a `stats.total` beside `pagination.page` is not\n * taken for the list's size. The array itself is never a stop field,\n * whatever it is called. The path follows the `dataPath` convention —\n * `has_more`, `result.total_pages` or `pagination.totalPages` — and spells\n * each segment as the document does (`pageInfo.hasNextPage`). When several\n * candidates exist, a `hasMore` boolean wins over a `totalPages` integer,\n * which wins over a `totalCount` integer; within one kind the first in scan\n * order wins. A candidate whose type does not fit its kind (a string\n * `total`) is ignored.\n */\nexport function detectEndOfIteration(\n  properties: Record<string, SchemaObject | undefined>,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationEndOfIteration | undefined {\n  const found = new Map<PaginationEndOfIteration['kind'], string>();\n  const record = (name: string, path: string, schema: SchemaObject): void => {\n    const kind = classifyEndField(name, schema, componentSchemas);\n    if (kind && !found.has(kind)) found.set(kind, path);\n  };\n\n  const segments = dataPath.split('.');\n  const arrayName = segments[segments.length - 1];\n  if (segments.length > 1) {\n    const parentPath = segments.slice(0, -1).join('.');\n    const parent = resolveSchemaPath({ properties }, parentPath, componentSchemas);\n    for (const [inner, innerSchema] of Object.entries(parent ? objectProperties(parent, componentSchemas) : {})) {\n      if (innerSchema && inner !== arrayName) record(inner, `${parentPath}.${inner}`, innerSchema);\n    }\n  }\n\n  const companions = Object.entries(properties).filter(\n    (entry): entry is [string, SchemaObject] => entry[0] !== dataPath && entry[1] !== undefined,\n  );\n  for (const [name, schema] of companions) record(name, name, schema);\n  for (const [name, schema] of companions) {\n    if (!looksLikePaginationMetadata(name)) continue;\n    for (const [inner, innerSchema] of Object.entries(objectProperties(schema, componentSchemas))) {\n      if (innerSchema) record(inner, `${name}.${inner}`, innerSchema);\n    }\n  }\n\n  for (const kind of END_KIND_PRIORITY) {\n    const path = found.get(kind);\n    if (path) return { kind, path };\n  }\n  return undefined;\n}\n\nfunction classifyEndField(\n  name: string,\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationEndOfIteration['kind'] | undefined {\n  // The name decides the kind, and only a named stop field has its schema\n  // read: a companion of any other name is never resolved at all.\n  const kind: PaginationEndOfIteration['kind'] | undefined = HAS_MORE_FIELDS.includes(name)\n    ? 'hasMore'\n    : TOTAL_PAGES_FIELDS.includes(name)\n      ? 'totalPages'\n      : TOTAL_COUNT_FIELDS.includes(name)\n        ? 'totalCount'\n        : undefined;\n  if (!kind) return undefined;\n  return endFieldFits(kind, resolveBareSchema(schema, componentSchemas)) ? kind : undefined;\n}\n\n/**\n * Whether a stop field's bare schema (`resolveBareSchema`) has the type its\n * kind is tested against: a `boolean` for `hasMore`, an `integer` or\n * `number` for `totalPages` and `totalCount`, under a type list too. The one\n * test for a field detection names and for one an override names.\n */\nfunction endFieldFits(kind: PaginationEndOfIteration['kind'], schema: SchemaObject): boolean {\n  return kind === 'hasMore' ? hasType(schema, 'boolean') : isNumeric(schema);\n}\n\n/**\n * Why an explicit `endOfIteration` cannot be read from a body whose\n * properties are `properties`, or `undefined` when it can. `properties` is\n * the map a detected stop field is read from — the body's own and every\n * `allOf` member's, through `$ref`s and nullable wrappers, as\n * `detectEndOfIteration` receives it — so an override and detection look at\n * one map: a field detection would read is one an override may name, and a\n * field it would not see is not there for an override either. `end.path` is\n * walked over that map as an explicit `dataPath` is (`resolveSchemaPath`:\n * through `$ref`s, `allOf` members and nullable wrappers at every further\n * segment), and the field it lands on must fit `end.kind` by the test\n * detection applies to a field it names (`endFieldFits`), under\n * `resolveBareSchema` as a detected one is. With no `properties` — an\n * operation whose primary response declares no body — the path resolves to\n * nothing.\n *\n * The text is the reason alone; the caller names the override's source and\n * the operation, and says what it does about it.\n */\nexport function endOfIterationProblem(\n  end: PaginationEndOfIteration,\n  properties: Record<string, SchemaObject | undefined> | undefined,\n  componentSchemas?: Record<string, SchemaObject>,\n): string | undefined {\n  const target = properties && resolveSchemaPath({ properties }, end.path, componentSchemas);\n  if (!target) return `endOfIteration path \"${end.path}\" does not resolve to a field in the response`;\n  if (endFieldFits(end.kind, resolveBareSchema(target, componentSchemas))) return undefined;\n  const expected = end.kind === 'hasMore' ? 'a boolean' : 'an integer or number';\n  return `endOfIteration path \"${end.path}\" is not ${expected} field, as kind \"${end.kind}\" requires`;\n}\n\nfunction hasType(schema: SchemaObject, type: string): boolean {\n  return Array.isArray(schema.type) ? schema.type.includes(type) : schema.type === type;\n}\n\nfunction isNumeric(schema: SchemaObject): boolean {\n  return hasType(schema, 'integer') || hasType(schema, 'number');\n}\n\n/**\n * The schema under every `$ref`, nullable wrapper and lone `allOf` member:\n * a `$ref` is followed to its component; a nullable wrapper — an OAS 3.1\n * type list naming `'null'`, OAS 3.0 `nullable: true`, a `oneOf`/`anyOf`\n * with one non-null variant — is stripped by `unwrapNullableSchema`, the\n * one definition the model side unwraps by; and an `allOf` with one member\n * that is what types the schema (`classifyInlineSchema`: a `$ref` member,\n * or an inline member with a type of its own — not an `allOf` of bare\n * limits beside the schema's own `type`) is read as that member exactly\n * when `schemaToTypeRef` types the schema as it (`readInlineAllOf`:\n * `'unwrapped'` or `'reference'`; a `required` beside a lone `$ref`\n * member to a component that declares properties makes the schema the\n * merged model, which is left as written), so\n * `has_more: { allOf: [{ $ref: Flag }], description }` with `Flag: { type:\n * boolean }` is a boolean here as it is in the IR. The three alternate\n * until the schema is\n * none of them, so `{ oneOf: [{ $ref: 'Tags' }, { type: 'null' }] }` with\n * `Tags: { type: ['array', 'null'], items }` reaches the array. Sibling\n * `properties` are folded into the `allOf` by the unwrap\n * (`foldSiblingProperties`), so a member with properties beside it is\n * never alone, and an `allOf` of several members is left as written for\n * the readers that merge them (`objectProperties`,\n * `collectObjectProperties`). A `$ref` met a second time\n * (`Flag: { oneOf: [{ $ref: Flag }, { type: 'null' }] }`) ends the walk on\n * the reference instead of looping on it, as `resolveSchemaKeyword` and\n * `objectProperties` stop; so does a `$ref` with no component map or to no\n * component. Shared by the stop-field check and the document walk an\n * explicit `dataPath` makes (`resolveDataPathFromSchema`), so a stop field\n * and a data array behind the same wrappers are read the same way.\n */\nexport function resolveBareSchema(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n  seen: Set<string> = new Set(),\n): SchemaObject {\n  if (schema.$ref) {\n    if (seen.has(schema.$ref)) return schema;\n    seen.add(schema.$ref);\n    const resolved = resolveComponentSchemaRef(schema, componentSchemas);\n    return resolved ? resolveBareSchema(resolved, componentSchemas, seen) : schema;\n  }\n  const bare = unwrapNullableSchema(schema);\n  if (bare.$ref) return resolveBareSchema(bare, componentSchemas, seen);\n  const lone =\n    bare.allOf?.length === 1 &&\n    classifyInlineSchema(bare) === 'allOf' &&\n    readInlineAllOf(bare.allOf, bare, componentSchemas) !== 'merged'\n      ? bare.allOf[0]\n      : undefined;\n  return lone ? resolveBareSchema(lone, componentSchemas, seen) : bare;\n}\n\nfunction isNullSchema(schema: SchemaObject): boolean {\n  return schema.type === 'null' || (Array.isArray(schema.type) && schema.type.every((t) => t === 'null'));\n}\n\n/**\n * The properties of an object schema as `collectObjectProperties` collects\n * them — the one walk through `$ref`s, `allOf` members and nullable wrappers,\n * with a name two members declare settled by `combineDeclarations` — for a\n * site that reads the properties alone. Anything that is not an object\n * yields none.\n */\nfunction objectProperties(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): Record<string, SchemaObject | undefined> {\n  return collectObjectProperties(schema, componentSchemas).properties;\n}\n\n/**\n * Every property the object `schema` describes declares, merged across its\n * `allOf` members, with the `required` lists that go with them — the one\n * walk through a composite schema: a list envelope's companions\n * (`extractListResponse`), a kept wrapper's stop field\n * (`bodyEndOfIteration`), a metadata companion's fields and the object\n * beside a nested array (`detectEndOfIteration`) and every segment of a\n * `dataPath` (`resolveSchemaPath`) are all read through it, so they see one\n * shape at every level.\n *\n * Every node the walk meets — the body, then each `allOf` member, however\n * deep — is read through `resolveBareSchema`, the resolver the explicit\n * `dataPath` walk reads the document with: a `$ref` is followed to its\n * component and a nullable wrapper of any spelling (a type list naming\n * `null`, OAS 3.0 `nullable: true`, a `oneOf`/`anyOf` with one non-null\n * variant) is stripped, however the two alternate. So fields an envelope\n * inherits from a shared base (`trace_id` on every response, say) are not\n * silently dropped whether the member is written `$ref: Base`, `{ oneOf: [{\n * $ref: Base }, { type: 'null' }] }`, a `$ref` to such a wrapper, or an\n * `allOf` nested inside one — and a stop field declared in any of them is\n * read. The one place the walk resolves a node, so the companions and the\n * stop field are read from the same shape, at every level, that the path\n * walk reaches the data array through. One `seen` runs through the whole\n * walk: the `$ref` strings `resolveBareSchema` records as it follows them,\n * handed to every call the walk makes, so a reference reached inside a\n * wrapper is as seen as one written on the member; and, for an inline\n * node, the schema object itself. No node is entered twice, under whatever\n * wrapper or at whatever depth it reappears, so a component that reaches\n * itself (`Base.allOf` holding `{ oneOf: [{ $ref: Base }, { type: 'null'\n * }] }`, or `{ $ref: Base }` outright), two components that reach each\n * other, and a document whose objects form a cycle are each read once and\n * end the walk where they repeat. An `allOf` member's own `properties`\n * beside its `allOf` are folded in as its first member\n * (`foldSiblingProperties`, through `unwrapNullableSchema`). A property\n * declared by more than one member is settled exactly as every `allOf`\n * merge settles it for a model's field (`combineDeclarations`): two inline\n * objects merge their properties — `pagination.next` from one member and\n * `pagination.total` from another both belong to the response, as they do\n * to the wrapper's model — two arrays keep the `items` that say something,\n * and otherwise the first declaration that declares a type types it, a\n * typeless one only annotating it. (Envelope detection reads the\n * members' own `properties`; a `oneOf`/`anyOf` member with more than one\n * non-null variant declares none, so it contributes nothing here. A body\n * that is not an envelope is merged by `mergeAllOfMembers`, which reads such\n * a member's variants.)\n */\nexport function collectObjectProperties(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): { properties: Record<string, SchemaObject>; required: string[] } {\n  const properties: Record<string, SchemaObject> = {};\n  const required: string[] = [];\n  const seenRefs = new Set<string>();\n  const seenNodes = new WeakSet<SchemaObject>();\n\n  const visit = (s: SchemaObject): void => {\n    if (seenNodes.has(s)) return;\n    seenNodes.add(s);\n    const bare = resolveBareSchema(s, componentSchemas, seenRefs);\n    // A reference the walk has followed already, or one nothing resolves:\n    // the walk ends on it, as the resolver did.\n    if (bare.$ref) return;\n    for (const sub of bare.allOf ?? []) visit(sub);\n    for (const [key, prop] of Object.entries(bare.properties ?? {})) {\n      if (!prop) continue;\n      const existing = properties[key];\n      properties[key] = existing ? combineDeclarations(existing, prop) : prop;\n    }\n    if (bare.required) required.push(...bare.required);\n  };\n  visit(schema);\n\n  return { properties, required };\n}\n\n// ---------------------------------------------------------------------------\n// Resolving a dotted `dataPath`\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a dotted property path (the `dataPath` convention) against a\n * response schema: each segment is looked up among the object's properties —\n * through `$ref`s, `allOf` members and nullable wrappers — and the schema it\n * lands on is returned with a final `$ref` resolved. `undefined` when a\n * segment is missing.\n */\nexport function resolveSchemaPath(\n  schema: SchemaObject,\n  path: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): SchemaObject | undefined {\n  let current: SchemaObject | undefined = schema;\n  for (const segment of path.split('.')) {\n    if (!current) return undefined;\n    current = objectProperties(current, componentSchemas)[segment];\n  }\n  if (!current) return undefined;\n  return resolveComponentSchemaRef(current, componentSchemas) ?? current;\n}\n\n/**\n * Resolve a dotted `dataPath` against the IR rather than the document: walk\n * from the response type through model fields, unwrapping nullables, and\n * return the element type of the array the path lands on. `models` is where\n * each model along the way is looked up by name, so the item type is exactly\n * the one the parser already assigned — the very `TypeRef` object the field\n * holds, which later renaming passes repoint in place. An empty `dataPath`\n * means `root` itself is the array. `undefined` when a segment is missing, a\n * model is unknown, or the path does not end on an array.\n */\nexport function resolveDataPathItemType(root: TypeRef, dataPath: string, models: Model[]): TypeRef | undefined {\n  let current: TypeRef = root;\n  for (const segment of dataPath === '' ? [] : dataPath.split('.')) {\n    const container = current.kind === 'nullable' ? current.inner : current;\n    if (container.kind !== 'model') return undefined;\n    const field = models.find((m) => m.name === container.name)?.fields.find((f) => f.name === segment);\n    if (!field) return undefined;\n    current = field.type;\n  }\n  const target = current.kind === 'nullable' ? current.inner : current;\n  return target.kind === 'array' ? target.items : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Explicit overrides — `x-pagination` and `operationHints[...].pagination`\n// ---------------------------------------------------------------------------\n\nconst STRATEGIES: ReadonlyArray<PaginationStrategy | 'none'> = ['cursor', 'offset', 'page', 'link-header', 'none'];\n\nexport interface PaginationOverrides {\n  /** The operation's `x-pagination` extension, exactly as written in the document. */\n  extension?: unknown;\n  /** `operationHints[\"METHOD /path\"].pagination` from the consumer's config. */\n  hint?: unknown;\n}\n\n/** The validated, merged override for one operation, with the source(s) it came from for warnings. */\nexport interface ResolvedPaginationOverride {\n  hint: PaginationHint;\n  source: string;\n}\n\n/**\n * Validate and merge the two override sources. Precedence per field: config\n * hint, then `x-pagination`; a source that fails validation is dropped with\n * an `[oagen] Warning:` and the other still applies. `undefined` when neither\n * source is present or usable.\n *\n * Resolved before the response is classified, because `strategy: 'none'`\n * must keep a list envelope from being unwrapped and an explicit `dataPath`\n * is resolved against the response while its schema is at hand.\n */\nexport function resolvePaginationOverride(\n  sources: PaginationOverrides,\n  opLabel: string,\n): ResolvedPaginationOverride | undefined {\n  const extension =\n    sources.extension === undefined ? undefined : validatePaginationHint(sources.extension, 'x-pagination', opLabel);\n  const hint =\n    sources.hint === undefined ? undefined : validatePaginationHint(sources.hint, 'operationHints pagination', opLabel);\n  if (!extension && !hint) return undefined;\n  const source = [extension && 'x-pagination', hint && 'operationHints pagination'].filter(Boolean).join(' / ');\n  return { hint: { ...extension, ...hint }, source };\n}\n\n/**\n * Layer the resolved override onto the detected pagination. A field the\n * override does not set keeps the detected value, so `{ strategy: 'page' }`\n * alone re-labels a detected offset iterator without restating its\n * parameters — except `param`, which is first looked for among the\n * operation's query parameters by the strategy's own names (`page` for\n * `page`, `cursor` or `after` for `cursor`, ...), so a strategy the override\n * names is driven by the parameter that fits it rather than by one detection\n * found for another strategy. `extras.overrideItemType` is the element type an explicit\n * `dataPath` resolved to; without it the detected item type (or the response\n * itself) stands. `extras.envelope` is the list envelope the response was\n * unwrapped on — `dataPath`, `dataDescription`, `itemType`, `envelopeFields`\n * as detection read them — whichever parameter drives the iterator: it is\n * read when `detected` is unset, so an override that creates the iterator\n * where the query parameters yielded none (`{ strategy: 'cursor', param:\n * 'c' }` on `{ data, has_more }`) still describes that envelope; when a\n * parameter was recognized, `detected` carries the same values and is read\n * first. `extras.endOfIteration` is the stop field read from the\n * response, which belongs to the iterator whether detection built one or the\n * override creates it from scratch (no paging parameter recognized, a\n * wrapper kept under an explicit `dataPath`): the override's own\n * `endOfIteration` wins, then the detected iterator's, then it.\n * `extras.pageStartOf` decides the first page for the page\n * parameter in use (default: `derivePageStart` on the IR parameter alone).\n *\n * Returns `detected` unchanged when there is no override or it is unusable —\n * no strategy or no `param` from any source, a `pageStart` under a strategy\n * other than `page`, a resolved `param`/`limitParam` the operation does not\n * declare as a query parameter, one parameter resolved as both — after an\n * `[oagen] Warning:` naming the problem (`resolveOverrideParams`). An\n * explicit `endOfIteration` is checked against the primary response before\n * this is reached (`endOfIterationProblem`, asked by `extractResponses`), so\n * one that arrives here resolves and fits. `strategy: 'none'` yields\n * `undefined`.\n */\nexport function applyPaginationOverride(\n  detected: PaginationMeta | undefined,\n  override: ResolvedPaginationOverride | undefined,\n  queryParams: Parameter[],\n  response: TypeRef,\n  opLabel: string,\n  extras: {\n    overrideItemType?: TypeRef;\n    envelope?: Pick<PaginationMeta, 'dataPath' | 'dataDescription' | 'itemType' | 'envelopeFields'>;\n    endOfIteration?: PaginationEndOfIteration;\n    pageStartOf?: PageStartResolver;\n  } = {},\n): PaginationMeta | undefined {\n  if (!override) return detected;\n  const merged = override.hint;\n  const where = `${override.source} on ${opLabel}`;\n\n  if (merged.strategy === 'none') return undefined;\n\n  const resolved = resolveOverrideParams(detected, merged, queryParams);\n  if ('problem' in resolved) {\n    warn(`${where}${resolved.problem}`);\n    return detected;\n  }\n  const { strategy, param, limitParam } = resolved;\n\n  // What detection read from the response: the detected iterator's own\n  // values, else the envelope unwrapped for an iterator only the override\n  // creates.\n  const list = detected ?? extras.envelope;\n  const dataPath = merged.dataPath ?? list?.dataPath;\n  // The data array's description belongs to the array detection unwrapped;\n  // it survives an override that keeps that array.\n  const dataDescription = dataPath === list?.dataPath ? list?.dataDescription : undefined;\n  const endOfIteration = merged.endOfIteration ?? detected?.endOfIteration ?? extras.endOfIteration;\n  // The page base belongs to the page parameter actually in use, which the\n  // override may have swapped, so it is derived from that parameter rather\n  // than carried over from detection.\n  const pageStartOf = extras.pageStartOf ?? derivePageStart;\n  const pageStart =\n    strategy === 'page' ? (merged.pageStart ?? pageStartOf(queryParams.find((p) => p.name === param))) : undefined;\n  return {\n    strategy,\n    param,\n    ...(limitParam !== undefined && { limitParam }),\n    ...(pageStart !== undefined && { pageStart }),\n    ...(dataPath !== undefined && { dataPath }),\n    ...(dataDescription !== undefined && { dataDescription }),\n    itemType: extras.overrideItemType ?? list?.itemType ?? (response.kind === 'array' ? response.items : response),\n    ...(list?.envelopeFields && { envelopeFields: list.envelopeFields }),\n    ...(endOfIteration && { endOfIteration }),\n  };\n}\n\n/**\n * The strategy, `param` and `limitParam` an override resolves to against\n * what was detected, or the reason it cannot apply (the text of the warning\n * `applyPaginationOverride` emits): no strategy from any source, a\n * `pageStart` under a strategy other than `page`, no `param` from any\n * source, a resolved `param` or `limitParam` the operation does not declare\n * as a query parameter, or one query parameter resolved as both. Shared with\n * `buildOperation`, which asks before classification whether an override\n * will be usable, so an override that will be rejected never changes how\n * the response is read.\n */\nexport function resolveOverrideParams(\n  detected: PaginationMeta | undefined,\n  merged: PaginationHint,\n  queryParams: Parameter[],\n): { strategy: PaginationStrategy; param: string; limitParam?: string } | { problem: string } {\n  const strategy = merged.strategy === 'none' ? undefined : (merged.strategy ?? detected?.strategy);\n  if (!strategy) return { problem: ' sets no strategy and none was detected — ignoring the override' };\n  // A first page number means nothing to an iterator that does not count\n  // pages, so one set for another strategy is a contradiction, not a field\n  // to drop quietly.\n  if (merged.pageStart !== undefined && strategy !== 'page') {\n    return {\n      problem: `: pageStart ${merged.pageStart} applies to the \"page\" strategy only, not to \"${strategy}\" — ignoring the override`,\n    };\n  }\n  const param = merged.param ?? declaredParamFor(strategy, queryParams) ?? detected?.param;\n  if (!param) {\n    return {\n      problem: `: strategy \"${strategy}\" needs a param, and none was given or detected — ignoring the override`,\n    };\n  }\n  const limitParam = merged.limitParam ?? detected?.limitParam;\n  // The resolved values are checked, not only the explicit ones: a `param`\n  // carried over from detection for another strategy is as undeclared as a\n  // misspelled one when the operation does not declare it.\n  for (const [key, name] of [\n    ['param', param],\n    ['limitParam', limitParam],\n  ] as const) {\n    if (name !== undefined && !queryParams.some((p) => p.name === name)) {\n      return { problem: `: ${key} \"${name}\" is not a query parameter of the operation — ignoring the override` };\n    }\n  }\n  // The two are checked against each other as resolved, so `{ param:\n  // 'limit' }` next to a detected `limitParam: 'limit'` is caught as surely\n  // as an override that names the same parameter twice: one parameter\n  // cannot carry both the page and the page size.\n  if (param === limitParam) {\n    return { problem: `: param and limitParam both name \"${param}\" — ignoring the override` };\n  }\n  return { strategy, param, ...(limitParam !== undefined && { limitParam }) };\n}\n\n/** The first query parameter the operation declares under one of `strategy`'s own parameter names, if any. */\nfunction declaredParamFor(strategy: PaginationStrategy, queryParams: Parameter[]): string | undefined {\n  const names =\n    strategy === 'cursor'\n      ? CURSOR_PARAMS\n      : strategy === 'offset'\n        ? OFFSET_PARAMS\n        : strategy === 'page'\n          ? PAGE_PARAMS\n          : [];\n  return names.map((name) => queryParams.find((p) => p.name === name)).find((p) => p !== undefined)?.name;\n}\n\n/**\n * Check one override object's shape. Returns the typed hint with only the\n * keys the author set, or `undefined` after a warning when any field is\n * malformed. An unknown key is reported and skipped without invalidating the\n * rest, and a key set to `undefined` counts as absent. What the fields say\n * about the operation — whether the parameters are declared, the `dataPath`\n * reaches an array, the `endOfIteration` resolves to a field of the fitting\n * type — is checked later, against the operation (`resolveOverrideParams`,\n * `endOfIterationProblem`).\n */\nexport function validatePaginationHint(raw: unknown, source: string, opLabel: string): PaginationHint | undefined {\n  const where = `${source} on ${opLabel}`;\n  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n    warn(`${where} must be an object — ignoring it`);\n    return undefined;\n  }\n\n  const out: PaginationHint = {};\n  for (const [key, value] of Object.entries(raw)) {\n    if (value === undefined) continue;\n    switch (key) {\n      case 'strategy':\n        if (typeof value !== 'string' || !(STRATEGIES as readonly string[]).includes(value)) {\n          const expected = STRATEGIES.map((s) => `\"${s}\"`).join(', ');\n          warn(`${where}: unknown strategy ${JSON.stringify(value)} (expected one of ${expected}) — ignoring it`);\n          return undefined;\n        }\n        out.strategy = value as PaginationStrategy | 'none';\n        break;\n      case 'param':\n      case 'limitParam':\n      case 'dataPath':\n        if (typeof value !== 'string' || value.trim() === '') {\n          warn(`${where}: ${key} must be a non-empty string — ignoring it`);\n          return undefined;\n        }\n        out[key] = value;\n        break;\n      case 'pageStart':\n        if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n          warn(`${where}: pageStart must be a non-negative integer — ignoring it`);\n          return undefined;\n        }\n        out.pageStart = value;\n        break;\n      case 'endOfIteration': {\n        const end = validateEndOfIteration(value);\n        if (!end) {\n          warn(\n            `${where}: endOfIteration must be { kind: \"hasMore\" | \"totalPages\" | \"totalCount\", path: string } — ignoring it`,\n          );\n          return undefined;\n        }\n        out.endOfIteration = end;\n        break;\n      }\n      default:\n        warn(`${where}: unknown key \"${key}\" skipped`);\n    }\n  }\n  return out;\n}\n\n/** The shape alone: a known `kind` and a non-empty `path`. Whether the path resolves is `endOfIterationProblem`'s question. */\nfunction validateEndOfIteration(value: unknown): PaginationEndOfIteration | undefined {\n  if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n  const { kind, path } = value as { kind?: unknown; path?: unknown };\n  if (!(END_KIND_PRIORITY as readonly unknown[]).includes(kind)) return undefined;\n  if (typeof path !== 'string' || path.trim() === '') return undefined;\n  return { kind: kind as PaginationEndOfIteration['kind'], path };\n}\n\nfunction warn(message: string): void {\n  console.warn(`[oagen] Warning: ${message}`);\n}\n\n/**\n * The type an iterator yields from `response`: the items of a top-level\n * array, under a nullable wrapper too (an OAS 3.0 `nullable: true` array\n * response is `nullable<array<T>>`), else the response itself.\n */\nexport function paginatedItemType(response: TypeRef): TypeRef {\n  const inner = response.kind === 'nullable' ? response.inner : response;\n  return inner.kind === 'array' ? inner.items : response;\n}\n","/**\n * Materialize an inline schema that is not a model field — a response\n * header, a `default`/`nXX` body, a secondary content type — under names no\n * other model owns, through the extractor every field goes through.\n *\n * The schema is extracted as if it were a property of a parent (or of no\n * parent), so every shape a field can take is materialized under the name\n * `schemaToTypeRef` references it by, by construction. The resulting models\n * are checked against a spec-wide registry of model shapes; the rules for a\n * taken name are the same everywhere this is used (see\n * `materializeInlineSchema`).\n */\nimport type { Model, TypeRef } from '../ir/types.js';\nimport { collectModelTypeRefs, renameModelRefs, renameTypeRefModels, walkTypeRef } from '../ir/types.js';\nimport { toPascalCase } from '../utils/naming.js';\nimport type { SchemaObject } from './schemas.js';\nimport { isComponentModelRef, schemaToTypeRef } from './schemas.js';\nimport {\n  extractInlineModelsFromProperties,\n  modelFingerprint,\n  modelShares,\n  qualifyInlineModelName,\n} from './inline-models.js';\n\n// The model-shape fingerprint lives beside the schema-shape key in\n// inline-models.ts, where the extractor compares models too; re-exported here\n// for the registry's readers.\nexport { modelFingerprint };\n\n/**\n * Spec-wide record of every name an inline model must not silently reuse:\n * the component models and the models their fields mint (seeded up front,\n * each with the model itself), each operation's primary response and\n * request body models, each header, body and parameter model materialized\n * so far — and every enum name, component or minted (`reserveEnumNames`),\n * since a model and an enum under one name reach an emitter as one public\n * symbol. A model's entry carries its shape fingerprint, so a model whose\n * shape the owner shares can take the name (`ownerShares`), and — for\n * operation-owned models — which operation produced it, so a collision\n * inside one operation can be told apart from one across operations. An\n * enum's entry carries `ENUM_NAME_FINGERPRINT`, which no model's fingerprint\n * equals, so a model minted under an enum's name always clashes and moves on.\n */\nexport type InlineModelRegistry = Map<string, InlineModelOwner>;\n\nexport interface InlineModelOwner {\n  fingerprint: string;\n  operation?: string;\n  /**\n   * The owner itself, for a model the document declares — a component schema\n   * or a model a component's field minted — which shares its name with every\n   * shape it admits (`modelShares`). Absent for an operation's model, which\n   * shares its name on an identical fingerprint only.\n   */\n  model?: Model;\n}\n\n/**\n * Whether the owner of a name shares it with `model`, whose fingerprint is\n * `fingerprint`: a declared model (`owner.model`) when it admits the shape\n * (`modelShares`: the same fields and types, the owner no stricter on\n * requiredness or nullability, everything else identical, the model's own\n * `deprecated` read apart — a live owner shares with a deprecated copy, a\n * deprecated owner only with a deprecated one), and an operation's model\n * when the fingerprints agree, flag included. A shape the SDK sends (`sent`:\n * a request body, a parameter) shares a declared model's name on an\n * identical shape only, the flag read the same way: typed as a looser\n * component, a caller could leave out what the operation requires. The one\n * question every clash check below asks.\n */\nexport function ownerShares(owner: InlineModelOwner, model: Model, fingerprint: string, sent = false): boolean {\n  return owner.model ? modelShares(owner.model, model, sent) : owner.fingerprint === fingerprint;\n}\n\n/**\n * The fingerprint an enum name is registered under. Every model fingerprint\n * (`modelFingerprint`) carries a `#` between its fields and the rest, so no\n * model can match this and share an enum's name.\n */\nexport const ENUM_NAME_FINGERPRINT = 'enum';\n\n/** Record every model of `models` the registry does not know yet as owned by `operation`; the first owner keeps a name. */\nexport function registerInlineModels(registry: InlineModelRegistry, models: Model[], operation?: string): void {\n  for (const model of models) {\n    if (registry.has(model.name)) continue;\n    registry.set(model.name, { fingerprint: modelFingerprint(model), operation });\n  }\n}\n\n/**\n * Record every name of `names` the registry does not know yet as an enum's,\n * so no inline model is materialized under it (`ENUM_NAME_FINGERPRINT`),\n * owned by `operation` when one of that operation's own references carries\n * the enum — so a deferred model of the operation that derives the name is\n * qualified by location, as one that clashes with the operation's models is\n * (`deferredNamingStem`) — and by no operation for a component enum's name\n * or one a component's field or a shared companion carries, which reads as\n * a clash with a component. A name a model or an earlier enum already owns\n * keeps its entry: the first owner keeps a name, and a model's is the\n * document's own clash, not one the registry can move.\n */\nexport function reserveEnumNames(registry: InlineModelRegistry, names: Iterable<string>, operation?: string): void {\n  for (const name of names) {\n    if (!registry.has(name)) registry.set(name, { fingerprint: ENUM_NAME_FINGERPRINT, operation });\n  }\n}\n\n/**\n * One site's settlement, kept for the sites of the same bare name after it:\n * the stem it settled on and, in order, every rename made under that stem —\n * the ones `renameClashing` made (`Circle` → `BodyCircle`) and the ones it\n * replayed from an earlier site. A later site trying the stem replays the\n * renames on its own trial before comparing (`runTrial`), so a schema\n * identical to the earlier site's builds exactly the earlier site's names\n * and shares every model; compared as extracted, its root would still\n * reference `Circle`, fingerprint differently from the earlier root, and a\n * second root and child would be minted.\n */\nexport interface SettledSite {\n  stem: string;\n  renames: ReadonlyArray<readonly [from: string, to: string]>;\n}\n\n/**\n * The settlements of the sites that derive from one bare name — the same\n * header on several status codes or operations, one media type's inline body\n * on several status codes — in the order the sites were resolved, one per\n * stem: the one container `materializeInlineSchema` writes to. The caller\n * creates it (`createSiblingSites`) and hands the same object to every site\n * of the bare name. Each call reads `settled`, tries those stems right after\n * the bare name (the bare name itself with the renames of the site that\n * settled on it), so a shape identical to an earlier site's shares that\n * site's model under whichever stem it took (`…Response200`, not a fresh\n * `…Response201`), and a different shape steps past them to the site's own\n * candidates; then it appends the site it settles — the only argument a call\n * mutates, and only this field of it.\n */\nexport interface SiblingSites {\n  /** The settlements so far, in the order the sites were resolved; appended to by `materializeInlineSchema`. */\n  readonly settled: SettledSite[];\n}\n\n/**\n * A settlement container for one bare name: empty, or seeded from `stems` —\n * the earlier string form (`SiblingStems`) read as settlements without\n * renames. The strings are copied, never written.\n */\nexport function createSiblingSites(stems: SiblingStems = []): SiblingSites {\n  return { settled: stems.map((stem) => ({ stem, renames: [] })) };\n}\n\n/**\n * The form `siblings` took before a settlement carried its renames: the\n * stems earlier sites settled on, and nothing else. Read-only in type\n * (`readonly`, so a push is a type error) and in fact: `materializeInlineSchema`\n * copies it into a container of its own (`siblingSitesOf`), to the same result\n * a `SiblingSites` would give, and records this call's settlement in that\n * private container only — the array given, empty or frozen, is never\n * touched. A caller that wants the sites after this one to see the settlement\n * creates a `SiblingSites` and passes it to each of them.\n */\nexport type SiblingStems = readonly string[];\n\n/**\n * The form `siblings` took between the string form and the container: a\n * bare list of settlements. Accepted so a caller on that form keeps\n * compiling. A non-empty list is used as the container's `settled` list\n * itself — this call appends to it, as it did then. An empty array has no\n * element to tell it from the string form, so it is read as that form:\n * read-only, never written (`siblingSitesOf`).\n */\nexport type SettledSites = SettledSite[];\n\nexport interface MaterializeInlineOptions {\n  /**\n   * The property name to extract the schema under for the `index`-th stem:\n   * the bare name first, then whatever qualifies it (a status code, an\n   * operation, a numeric suffix). `firstClashOwners` is who owned the names\n   * the first trial clashed with, for a caller that orders its candidates by\n   * where the clash came from; empty while nothing has clashed.\n   */\n  stem: (index: number, firstClashOwners: InlineModelOwner[]) => string;\n  /**\n   * The settlements of the earlier sites of the same bare name, whose stems\n   * are tried between the bare name and the caller's other candidates with\n   * their renames replayed, and which this site's settlement is appended to:\n   * a `SiblingSites` container the caller created, or a non-empty bare list\n   * of settlements (`SettledSites`) — in either, the settled list is the one\n   * thing this call mutates — or the read-only string form, `SiblingStems`,\n   * copied into a container of this call's own; an empty array is read as\n   * the string form. Absent, only the caller's candidates are tried and\n   * nothing is recorded.\n   */\n  siblings?: SiblingSites | SettledSites | SiblingStems;\n  /** The parent the schema is a property of; none for a body. */\n  parentName?: string;\n  componentSchemas?: Record<string, SchemaObject>;\n  registry: InlineModelRegistry;\n  /** Recorded as the owner of every model registered here. */\n  operation?: string;\n  /** The schema is what the SDK sends (a request body, a parameter): a component shares its name only on an identical shape (`ownerShares`). */\n  sent?: boolean;\n  /** Where the materialized models go. */\n  models: Model[];\n}\n\n/**\n * Attempts before the loop gives up moving names and numbers the clashing\n * ones in place. Each attempt either reserves names or advances the stem, and\n * the fixed-point test below stops it long before this; the cap is the\n * guarantee that no input can keep it going.\n */\nconst MAX_ATTEMPTS = 32;\n\n/**\n * Rename rounds before settling gives up. Every rename picks a name nothing\n * owns and nothing in the trial uses, so each round settles at least one\n * model for good and the rounds end within the trial's size; the cap only\n * backs that.\n */\nconst MAX_RENAME_ROUNDS = 64;\n\n/**\n * Type `schema` and materialize every model it names into `options.models`,\n * under names the registry does not already give another shape.\n *\n * A trial extracts the schema under the current stem and compares every model\n * it minted with the registry: a name whose owner shares it (`ownerShares`:\n * a component or a component field's model admits the shape, an operation's\n * model has the identical one) is shared, so a header or body a component\n * admits simply references it; any other owned name clashes. On a clash the\n * loop makes the cheapest move that can still change something:\n *\n *   1. reserve the clashing names — a `oneOf`/`anyOf` variant named from its\n *      own `title` or const (`Circle`) is minted from the schema, not the\n *      stem, so no stem would move it; reserved, variant naming steps around\n *      it the way it steps around a sibling's model (`CircleListPetsDefault…`);\n *   2. when every clashing name is already reserved and still minted (the\n *      root, nested objects, array items: names derived from the stem),\n *      advance the stem (`…2`, `…3`, or the caller's qualified candidates).\n *\n * The clashing set is compared between attempts: when a stem advance leaves\n * it unchanged, neither move can clear it (a titled variant nested below the\n * top level, where the reservation does not reach) — the fixed point — and\n * the loop stops rather than retrying forever. The earlier trial is then kept\n * and settled in place (`renameClashing`): the clashing names themselves are\n * renamed, qualified by the root model name (`ListPetsDefaultResponseCircle`)\n * then numbered, with every reference among the trial's models and in the\n * returned type rewritten to match; and because renaming a child changes its\n * parent's shape, the trial is checked again on its new fingerprints, so a\n * parent that matched a registered model before and differs from it now\n * moves to the next free stem with its children, instead of being dropped at\n * commit as already defined. That rewrite cannot tell an inline model's\n * reference from a `$ref` to a component MODEL of the same name, so a schema\n * that both inlines a clashing `Circle` and references component model\n * `Circle` fails loudly instead (`componentModelRefTargets`). A component\n * ENUM of the name is no such bar: a `$ref` to it is an `EnumRef`, which the\n * rewrite never touches, so the inline `Circle` is renamed under the root\n * and the enum reference stays. A rename replayed from an earlier site that\n * such a `$ref` to a component model would make unsafe is skipped, not failed\n * (`runTrial`).\n *\n * The stems are tried in the order `candidateStem` gives: the caller's bare\n * name, then the stems earlier sites of the same bare name settled on\n * (`options.siblings`), then the caller's own qualified candidates. A trial\n * under an earlier site's stem replays that site's renames first, so the\n * `application/vnd.pet+json` body of a 201 whose bare name a component owns\n * tries the `…Response200` its 200 settled on before its own `…Response201`,\n * and shares the 200's models when the shapes are identical — nested\n * `…Response200Circle` included — where a name-only comparison would mint a\n * second model of the same shape. The site's own settlement — the stem the\n * trial was under or the one its root moved to, with the renames made under\n * it — is appended to `options.siblings` for the sites after it.\n */\nexport function materializeInlineSchema(schema: SchemaObject, given: MaterializeInlineOptions): TypeRef {\n  const options: ResolvedOptions = { ...given, siblings: siblingSitesOf(given.siblings) };\n  const { registry } = options;\n  const reserved = new Set<string>();\n  let stemIndex = 0;\n  let firstClashOwners: InlineModelOwner[] = [];\n  const candidateAt = (index: number): Candidate => candidateStem(index, options, firstClashOwners);\n  // The last clashing trial and the move made after it.\n  let previous: { trial: Trial; move: 'reserve' | 'stem' } | undefined;\n\n  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n    const trial = runTrial(schema, candidateAt(stemIndex), reserved, options);\n    if (trial.clashing.length === 0) return commit(trial, options);\n\n    if (firstClashOwners.length === 0) {\n      firstClashOwners = trial.clashing.map((name) => registry.get(name)).filter((o): o is InlineModelOwner => !!o);\n    }\n    const unreserved = trial.clashing.filter((name) => !reserved.has(name));\n    if (unreserved.length > 0) {\n      for (const name of unreserved) reserved.add(name);\n      previous = { trial, move: 'reserve' };\n      continue;\n    }\n    if (previous?.move === 'stem' && sameNames(previous.trial.clashing, trial.clashing)) {\n      // The stem advance changed nothing: the fixed point. The earlier of the\n      // two identical trials carries the lower stem, so it is the one kept.\n      return commit(renameClashing(previous.trial, options, candidateAt), options);\n    }\n    stemIndex++;\n    previous = { trial, move: 'stem' };\n  }\n\n  return commit(renameClashing(previous!.trial, options, candidateAt), options);\n}\n\n/** `MaterializeInlineOptions` with `siblings` in the one form the loop reads (`siblingSitesOf`). */\ninterface ResolvedOptions extends Omit<MaterializeInlineOptions, 'siblings'> {\n  siblings?: SiblingSites;\n}\n\n/**\n * `siblings` as the loop reads it, the three accepted forms told apart by\n * shape, never by emptiness: the `SiblingSites` container as given (it\n * carries `settled`) — the very object, since this call's settlement is\n * appended to it; a non-empty array of settlement objects (`SettledSites`),\n * wrapped as the container's settled list itself, so the call appends to the\n * caller's list as it did on that form; and an array of strings\n * (`SiblingStems`) — an empty array among them, which has no element to say\n * otherwise — copied into a fresh container (`createSiblingSites`), so the\n * array given is only read. Absent stays absent.\n */\nfunction siblingSitesOf(siblings: SiblingSites | SettledSites | SiblingStems | undefined): SiblingSites | undefined {\n  if (siblings === undefined) return undefined;\n  if ('settled' in siblings) return siblings;\n  if (siblings.length > 0 && typeof siblings[0] !== 'string') return { settled: siblings as SettledSites };\n  return createSiblingSites(siblings as SiblingStems);\n}\n\n/** A stem to try, with the renames to replay on the trial extracted under it (none for the caller's own candidates). */\ninterface Candidate {\n  stem: string;\n  renames: SettledSite['renames'];\n}\n\n/**\n * The `index`-th candidate to try: the caller's bare name (its first\n * candidate) — with the renames of the earlier site that settled on that\n * very stem, when one did — then each other stem an earlier site of the same\n * bare name settled on (`options.siblings`), with its renames, then the\n * caller's other candidates in the caller's order, leaving out any stem a\n * sibling settled on — the same stem tried twice in a row would read to the\n * fixed-point test as an advance that changed nothing. The caller's\n * candidates end in an unbounded numbered run, so at most as many of them as\n * there are siblings are left out and the search is bounded; past the bound\n * the caller's own `index`-th candidate is the fallback.\n */\nfunction candidateStem(index: number, options: ResolvedOptions, firstClashOwners: InlineModelOwner[]): Candidate {\n  const own = (i: number): string => options.stem(i, firstClashOwners);\n  const bare = own(0);\n  const sites = options.siblings?.settled ?? [];\n  if (index === 0) return { stem: bare, renames: sites.find((site) => site.stem === bare)?.renames ?? [] };\n  const others = sites.filter((site) => site.stem !== bare);\n  if (index <= others.length) return others[index - 1];\n  let remaining = index - others.length;\n  for (let i = 1; i <= index + others.length; i++) {\n    const stem = own(i);\n    if (others.some((site) => site.stem === stem)) continue;\n    if (--remaining === 0) return { stem, renames: [] };\n  }\n  return { stem: own(index), renames: [] };\n}\n\ninterface Trial {\n  schema: SchemaObject;\n  propertyName: string;\n  reserved: ReadonlySet<string> | undefined;\n  models: Model[];\n  fingerprints: Map<Model, string>;\n  /** Names the registry gives another shape, sorted. */\n  clashing: string[];\n  /** Set once the trial's references have been rewritten and the type must not be rebuilt. */\n  type?: TypeRef;\n  /**\n   * The stem the root is settled under — the trial's own, or the one the root\n   * moved to in `renameClashing`; unset when the root was numbered in place\n   * and no stem names it. Recorded for the site's siblings at commit.\n   */\n  settledStem: string | undefined;\n  /** Every rename made on the trial so far, in order: replayed from an earlier site, then `renameClashing`'s own. */\n  renames: Array<readonly [string, string]>;\n}\n\n/**\n * Extract the schema under the candidate's stem and compare every model with\n * the registry. The candidate's renames — an earlier site's, see\n * `SettledSite` — are replayed first, each only where it applies: the model\n * to move must be among the trial's, the name moved to free in it, and the\n * name moved not one this schema `$ref`s as a component model\n * (`renameModel`), so a schema that differs from the earlier site's (no\n * `Circle` to move, a model of its own already named `BodyCircle`, or an\n * inline `Circle` beside a `$ref` to component `Circle`, which the rewrite\n * could not tell apart) is compared as extracted and settles on its own\n * merits — an inline `Circle` of the component's shape shares the component,\n * and the root takes the site's own next candidate — rather than failing the\n * parse. A replayed rename rewrites the type as the settling pass does, so\n * the type is kept with the trial.\n */\nfunction runTrial(\n  schema: SchemaObject,\n  candidate: Candidate,\n  reservedNames: Set<string>,\n  options: ResolvedOptions,\n): Trial {\n  const { stem: propertyName } = candidate;\n  const reserved = reservedNames.size > 0 ? new Set(reservedNames) : undefined;\n  const models: Model[] = [];\n  extractInlineModelsFromProperties(\n    { properties: { [propertyName]: schema } },\n    models,\n    options.parentName,\n    options.componentSchemas,\n    undefined,\n    reserved,\n  );\n  const renames: Array<readonly [string, string]> = [];\n  let type: TypeRef | undefined;\n  if (candidate.renames.length > 0) {\n    const rewritten = schemaToTypeRef(schema, propertyName, options.parentName, undefined, reserved);\n    const referenced = componentModelRefTargets(rewritten, models);\n    for (const [from, to] of candidate.renames) {\n      if (!models.some((model) => model.name === from) || models.some((model) => model.name === to)) continue;\n      if (!renameModel(models, rewritten, referenced, from, to)) continue;\n      renames.push([from, to]);\n    }\n    if (renames.length > 0) type = rewritten;\n  }\n  const fingerprints = new Map(models.map((model) => [model, modelFingerprint(model)]));\n  const clashing = models\n    .filter((model) => {\n      const owner = options.registry.get(model.name);\n      return owner !== undefined && !ownerShares(owner, model, fingerprints.get(model)!, options.sent);\n    })\n    .map((model) => model.name)\n    .sort();\n  return { schema, propertyName, reserved, models, fingerprints, clashing, type, settledStem: propertyName, renames };\n}\n\nfunction sameNames(a: string[], b: string[]): boolean {\n  return a.length === b.length && a.every((name, i) => name === b[i]);\n}\n\n/**\n * Register and emit the trial's new models. A name the registry already owns\n * is shared only when the owner shares it (`ownerShares`) — decided on the\n * trial's final models, after every rename — so a model whose references were\n * rewritten is never dropped as \"already defined\" in favour of an owner that\n * no longer matches it. A deprecated model a live declared owner shares its\n * name with is dropped the same way, with the warning the merge passes give\n * such a copy, once per site. The trial has no such clash left when it gets here\n * (`runTrial` found none, or `renameClashing` cleared them all), so the\n * remaining branch is a guard against a regression, not an expected path.\n * The site's settlement — the stem it settled on and the renames made under\n * it — is recorded for its siblings, whether it minted models or shared every\n * one of them; a stem an earlier site already recorded keeps that site's.\n */\nfunction commit(trial: Trial, options: ResolvedOptions): TypeRef {\n  for (const model of trial.models) {\n    const fingerprint = trial.fingerprints.get(model)!;\n    const owner = options.registry.get(model.name);\n    if (owner && ownerShares(owner, model, fingerprint, options.sent)) {\n      // A deprecated copy a live declared model admits is announced once per\n      // site, as the merge passes announce one (`settleSharedNames`).\n      if (model.deprecated && owner.model && !owner.model.deprecated) {\n        console.warn(\n          `[oagen] Warning: Inline model \"${model.name}\" is declared both deprecated and live with the same shape — keeping the live definition under the shared name`,\n        );\n      }\n      continue;\n    }\n    if (owner !== undefined) {\n      throw new Error(\n        `Inline model \"${model.name}\" would overwrite a model of another shape; this is a bug in materializeInlineSchema.`,\n      );\n    }\n    options.registry.set(model.name, { fingerprint, operation: options.operation });\n    options.models.push(model);\n  }\n  const { siblings } = options;\n  const { settledStem } = trial;\n  if (siblings && settledStem !== undefined && !siblings.settled.some((site) => site.stem === settledStem)) {\n    siblings.settled.push({ stem: settledStem, renames: [...trial.renames] });\n  }\n  return trial.type ?? schemaToTypeRef(trial.schema, trial.propertyName, options.parentName, undefined, trial.reserved);\n}\n\n/**\n * Rename, in place, the model named `from` among `models` to `to` and rewrite\n * every reference to it — in the models' fields, in `type`, and in the inline\n * enums named from it (`CircleStatus` → `BodyCircleStatus`, since a component\n * enum `CircleStatus` of other values would otherwise be collected first and\n * the renamed model's field would point at it). Returns `false`, having\n * changed nothing, when `from` is a name the schema also `$ref`s as a\n * component model (`referenced`, see `componentModelRefTargets`): the rewrite\n * cannot tell the inline reference from the `$ref`, so the rename is unsafe\n * and the caller decides — the settling pass fails loudly, a sibling's replay\n * skips it (`runTrial`).\n */\nfunction renameModel(\n  models: readonly Model[],\n  type: TypeRef,\n  referenced: ReadonlySet<string>,\n  from: string,\n  to: string,\n): boolean {\n  if (referenced.has(from)) return false;\n  const renames = new Map([[from, to]]);\n  for (const model of models) {\n    if (model.name === from) {\n      model.name = to;\n      // The inline enums of its fields were named from it (`CircleStatus`),\n      // so they follow (`ListPetsDefaultResponseCircleStatus`): left as they\n      // were, a component enum `CircleStatus` of other values would be\n      // collected first and the renamed model's field would point at it.\n      for (const field of model.fields) rewriteEnumPrefix(field.type, from, to);\n    }\n    // Fields, variants and discriminator mappings alike.\n    renameModelRefs(model, renames);\n  }\n  renameTypeRefModels(type, renames);\n  return true;\n}\n\n/**\n * Settle the fixed-point trial in place so it can be committed as it stands:\n * rename every model whose name the registry gives another shape, rewrite\n * every reference to it among the trial's models and in the returned type,\n * and check again, since renaming a child changes its parent's shape. Round\n * by round, until no name is owned by another shape:\n *\n *   - a clashing name other than the root — a titled or const-named variant\n *     the reservation did not reach — is qualified by the root model name\n *     (`ListPetsDefaultResponseCircle`), or kept as is when it already starts\n *     with it, then numbered until free;\n *   - a clashing root — its shape changed when a child under it moved, so a\n *     registered model of that name no longer matches it — moves the body to\n *     the next free stem the caller would have tried next\n *     (`ListPetsDefaultResponse2`; a header's qualified candidates), and with\n *     it every model named under it (`ListPetsDefaultResponse2Circle`), as a\n *     stem advance would have named them — except one whose name an\n *     owner that shares it already holds (`ownerShares`), which stays shared\n *     under that name with the moved parent still referencing it, exactly as\n *     it is shared when nothing moves.\n *\n * Every new name is one nothing owns and nothing in the trial uses, so a\n * renamed model can never clash again, a shared model never changes and so\n * never starts a round, and the rounds end within the trial's size. A name\n * the schema also `$ref`s as a component model cannot be rewritten safely\n * (see `materializeInlineSchema`) and fails loudly.\n *\n * `candidateAt` gives the stems in the order the loop tried them\n * (`candidateStem`), so a moved root takes the next free one of those; the\n * stem it moved to is the one recorded for the site's siblings, and a root\n * numbered in place when none is free records none. Every rename made here\n * is appended to the trial's, after any replayed from an earlier site, so a\n * later site can replay them all in order.\n */\nfunction renameClashing(trial: Trial, options: ResolvedOptions, candidateAt: (index: number) => Candidate): Trial {\n  const { registry } = options;\n  const rootOf = (propertyName: string): string =>\n    qualifyInlineModelName(toPascalCase(propertyName), options.parentName);\n  let rootName = rootOf(trial.propertyName);\n  let settledStem = trial.settledStem;\n  // A trial that replayed an earlier site's renames carries its rewritten type.\n  const type =\n    trial.type ?? schemaToTypeRef(trial.schema, trial.propertyName, options.parentName, undefined, trial.reserved);\n  const referenced = componentModelRefTargets(type, trial.models);\n  const taken = new Set([...registry.keys(), ...trial.models.map((m) => m.name)]);\n\n  /** `candidate(1)`, `candidate(2)`, ... until one nothing owns or uses; claimed. */\n  const claim = (candidate: (n: number) => string): string => {\n    let n = 1;\n    let name = candidate(n);\n    while (taken.has(name)) name = candidate(++n);\n    taken.add(name);\n    return name;\n  };\n  const rename = (from: string, to: string): void => {\n    // Only a reference to a component MODEL of this name is indistinguishable\n    // from the inline model's own references once both are plain names; a\n    // reference to a component enum of the name is an `EnumRef`, which the\n    // rewrite never touches, so the inline model is simply renamed past it.\n    if (!renameModel(trial.models, type, referenced, from, to)) {\n      throw new Error(\n        `Inline schema \"${from}\" under ${rootName} has another shape than component \"${from}\", which the same ` +\n          `schema also references; rename the inline schema's title or the component so the two can be told apart.`,\n      );\n    }\n    trial.renames.push([from, to]);\n  };\n\n  let fingerprints = trial.fingerprints;\n  let clashing = trial.clashing;\n  for (let round = 0; clashing.length > 0; round++) {\n    if (round >= MAX_RENAME_ROUNDS) {\n      throw new Error(\n        `Could not settle the inline models under ${rootName} in ${MAX_RENAME_ROUNDS} rounds; ` +\n          `this is a bug in materializeInlineSchema.`,\n      );\n    }\n    if (clashing.includes(rootName)) {\n      const oldRoot = rootName;\n      let movedRoot: string | undefined;\n      settledStem = undefined;\n      for (let index = 1; index <= MAX_RENAME_ROUNDS && movedRoot === undefined; index++) {\n        const { stem } = candidateAt(index);\n        const candidate = rootOf(stem);\n        if (!taken.has(candidate)) {\n          movedRoot = candidate;\n          settledStem = stem;\n        }\n      }\n      if (movedRoot === undefined) movedRoot = claim((n) => `${oldRoot}${n + 1}`);\n      taken.add(movedRoot);\n      // Decided per model, by shape: a model named under the root whose name\n      // an owner that shares it already holds (a component that admits it,\n      // an earlier operation's identical model) stays shared under that\n      // name, exactly as it would had the root not moved, and the moved\n      // parent keeps referencing it. The root itself, and every other model\n      // named under it, moves.\n      const moving = trial.models\n        .filter((model) => {\n          if (model.name === oldRoot) return true;\n          if (!model.name.startsWith(oldRoot)) return false;\n          const owner = registry.get(model.name);\n          return owner === undefined || !ownerShares(owner, model, fingerprints.get(model)!, options.sent);\n        })\n        .map((model) => model.name);\n      for (const name of moving) {\n        const suffix = name.slice(oldRoot.length);\n        rename(name, name === oldRoot ? movedRoot : claim((n) => `${movedRoot}${suffix}${n === 1 ? '' : n}`));\n      }\n      rootName = movedRoot;\n    } else {\n      for (const name of clashing) {\n        const base = name.startsWith(rootName) ? name : `${rootName}${name}`;\n        rename(\n          name,\n          claim((n) => `${base}${n === 1 ? '' : n}`),\n        );\n      }\n    }\n\n    fingerprints = new Map(trial.models.map((model) => [model, modelFingerprint(model)]));\n    clashing = trial.models\n      .filter((model) => {\n        const owner = registry.get(model.name);\n        return owner !== undefined && !ownerShares(owner, model, fingerprints.get(model)!, options.sent);\n      })\n      .map((model) => model.name)\n      .sort();\n  }\n\n  return { ...trial, fingerprints, clashing: [], type, settledStem };\n}\n\n/** Rename, in place, every inline enum under `ref` whose name was built from `oldPrefix` so it is built from `newPrefix`. */\nfunction rewriteEnumPrefix(ref: TypeRef, oldPrefix: string, newPrefix: string): void {\n  walkTypeRef(ref, {\n    enum: (r) => {\n      if (r.values && r.name.startsWith(oldPrefix))\n        (r as { name: string }).name = newPrefix + r.name.slice(oldPrefix.length);\n    },\n  });\n}\n\n/**\n * The names of the component models `type` and the fields of `models`\n * reference: every `ModelRef` that `schemaToTypeRef` built from a `$ref`\n * (`isComponentModelRef`, an identity mark). Only such a reference is\n * indistinguishable from an inline model's own references once the inline\n * model is renamed, so only these block a rename. A `$ref` to a component\n * enum is an `EnumRef`, which `renameTypeRefModels` leaves alone, so it is never\n * collected. One predicate for both renames — the settling pass and a\n * sibling's replay — so the two agree on which `$ref` a rename could hit.\n */\nfunction componentModelRefTargets(type: TypeRef, models: readonly Model[]): Set<string> {\n  const targets = new Set<string>();\n  const collect = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      model: (r) => {\n        if (isComponentModelRef(r)) targets.add(r.name);\n      },\n    });\n  };\n  collect(type);\n  for (const model of models) for (const ref of collectModelTypeRefs(model)) collect(ref);\n  return targets;\n}\n","import type { TypeRef, Model, Field, PaginationEndOfIteration, StatusRange } from '../ir/types.js';\nimport { toPascalCase, singularize } from '../utils/naming.js';\nimport {\n  collectObjectProperties,\n  detectEndOfIteration,\n  endOfIterationProblem,\n  END_OF_ITERATION_FIELDS,\n  looksLikePaginationMetadata,\n  resolveBareSchema,\n  resolveSchemaPath,\n} from './pagination.js';\nimport type { SchemaObject } from './schemas.js';\nimport {\n  arraySchemaOf,\n  declaresNull,\n  schemaToTypeRef,\n  buildFieldFromSchema,\n  classifyInlineSchema,\n  constraintsEntry,\n  deprecatedEntry,\n  foldSiblingProperties,\n  isArrayComponentRef,\n  isArraySchema,\n  collapsedNullableBranch,\n  typesAsUnknown,\n  warnOnUncarriedProperties,\n  withWrapperDocs,\n} from './schemas.js';\nimport type { EnvelopeCompanion } from './envelope-companion-names.js';\nimport {\n  collectProperties,\n  combineDeclarations,\n  extractInlineModelsFromProperties,\n  mergeAllOfMembers,\n  mergedObjectSchema,\n  readInlineAllOf,\n  unwrappedAllOfMember,\n} from './inline-models.js';\nimport { externalDocsEntry } from './external-docs.js';\nimport { schemaExtensionsEntry } from './extensions.js';\nimport { materializeInlineSchema, type InlineModelRegistry } from './materialize-inline.js';\n\n/**\n * What settles an array body's or list envelope's item models against the\n * names already decided (see `typeInlineItems`): the spec-wide registry of\n * model shapes the operations fill as they are read, and the operation to\n * record this body's models under.\n */\nexport interface ItemSettlement {\n  registry: InlineModelRegistry;\n  operation: string;\n}\n\nexport interface ResponseExtractionResult {\n  /** The TypeRef to use as the operation's response type */\n  response: TypeRef;\n  /** Any inline models discovered during extraction (to merge into ir.models) */\n  inlineModels: Model[];\n  /** Whether this response indicates a paginated list */\n  isPaginated: boolean;\n  /**\n   * Set when the body is a list envelope detection recognized but did not\n   * unwrap because nothing pages it (`paginationDisabled`): it was read as\n   * any other body, a plain response model carrying every field. The caller\n   * warns about an envelope kept for want of a paging parameter; one kept by\n   * `strategy: 'none'` was asked for.\n   */\n  unpagedEnvelope?: boolean;\n  /** Path to the data array within the response envelope (e.g., 'data') */\n  dataPath?: string;\n  /**\n   * The data array property's own description (see\n   * `PaginationMeta.dataDescription`). Set only for a list envelope whose\n   * data property declares one.\n   */\n  dataDescription?: string;\n  /** TypeRef of individual items in a paginated list */\n  itemType?: TypeRef;\n  /**\n   * The envelope's properties other than the data array (see\n   * `PaginationMeta.envelopeFields`). Set only for a list envelope.\n   */\n  envelopeFields?: Field[];\n  /**\n   * The field that ends an iteration, when the body declares an obvious one\n   * (see `PaginationMeta.endOfIteration`): read beside the array a list\n   * envelope was unwrapped on, and beside the array an explicit `dataPath`\n   * names in a body kept as a wrapper — a `$ref` to a component, an envelope\n   * detection would unwrap on another array, an inline body detection did\n   * not recognize (`bodyEndOfIteration`). Unset for every other body.\n   */\n  endOfIteration?: PaginationEndOfIteration;\n  /**\n   * Models lifted from inline companion objects, still under their\n   * operation-qualified names. They are deliberately not in `inlineModels`:\n   * `resolveEnvelopeCompanionNames` decides their final names once every list\n   * operation has been extracted.\n   */\n  envelopeCompanions?: EnvelopeCompanion[];\n}\n\nexport interface ResponseClassificationOptions {\n  /**\n   * Nothing will page the operation: its pagination was switched off\n   * explicitly (`strategy: 'none'`), or no query parameter it declares\n   * drives an iterator and no override names one. A list envelope is then\n   * not unwrapped: the body becomes a plain response model carrying every\n   * field, exactly as a non-list body does, so the wire shape survives\n   * without a `pagination` entry to describe it (`unpagedEnvelope` says it\n   * was an envelope).\n   */\n  paginationDisabled?: boolean;\n  /**\n   * An explicit `dataPath`, already known to reach an array in the body. One\n   * that restates the path a list envelope is unwrapped on changes nothing.\n   * Any other keeps the body as the wrapper the override iterates — a\n   * recognized envelope, kept exactly as under `paginationDisabled` since\n   * detection was wrong for this operation; an inline body detection did not\n   * recognize; a `$ref` to a component — so `response` is what the wire\n   * returns, the override says where the items are in it, and the wrapper\n   * carries the companions. The wrapper's stop field is still read, keyed by\n   * the override, whatever the wrapper is (`bodyEndOfIteration`). Read only\n   * when `paginationDisabled` is not set: `strategy: 'none'` leaves no\n   * iterator to stop.\n   */\n  dataPathOverride?: string;\n  /**\n   * With it, the items of an array body or a list envelope are typed under\n   * the first `<Op>Item` candidate the registry does not give another shape,\n   * and an identical shape shares the model it finds (`typeInlineItems`).\n   * Absent — a dry run that only reads names, a direct call — the items take\n   * `<Op>Item` as written.\n   */\n  settle?: ItemSettlement;\n}\n\n/**\n * The readings an inline body can take, one per way `buildOperation` decides\n * it (`iteratorSource`): unwrapped on its data array for an iterator a\n * declared query parameter or a usable override drives, or kept as the wire\n * shape — `strategy: 'none'`, nothing to page with, an explicit `dataPath`\n * naming another array (the same reading as `paginationDisabled`, so the\n * same names). A body that is no list envelope reads the same under both.\n * Which reading an operation takes is known only when it is read, so a dry\n * run that reserves a body's names (`bodyModelNames`) classifies it under\n * every reading here: whichever the operation then picks, the names it mints\n * are the reserved ones.\n */\nexport const BODY_READINGS: readonly ResponseClassificationOptions[] = [{}, { paginationDisabled: true }];\n\n/**\n * The word that stands in for a range key wherever a status code would\n * qualify a name: the header models and enums of a `4XX` response are\n * `…ClientError`, and the inline body of a `1XX`–`3XX` response is\n * `<Op><Label>Response` (`<Op>SuccessResponse`), as a `default` body is\n * `<Op>DefaultResponse`. The key itself cannot be used in these names —\n * `toPascalCase('4XX')` is `4Xx`. The inline body of a `4XX` or `5XX`\n * response is an error body (`isErrorStatusRange`), named `<Op>Error4Xx`\n * from the key itself, as a 404's is `<Op>Error404`.\n */\nexport const STATUS_RANGE_LABELS: Record<StatusRange, string> = {\n  '1XX': 'Informational',\n  '2XX': 'Success',\n  '3XX': 'Redirect',\n  '4XX': 'ClientError',\n  '5XX': 'ServerError',\n};\n\n/**\n * Whether a range response is an error response: `4XX` and `5XX` are, as\n * every status code they cover is an error (400–599); `1XX`–`3XX` are not.\n * The one answer for every place a range body is named: its inline body is\n * named and stepped as an explicit error status code's body is\n * (`<Op>Error4Xx`, then `<Op>Error4XxBody`; `<Op>Error4Xx<MediaType>` under\n * a secondary media type), while a `1XX`–`3XX` body keeps the range's label\n * (`<Op>SuccessResponse`).\n */\nexport function isErrorStatusRange(range: StatusRange): boolean {\n  return range === '4XX' || range === '5XX';\n}\n\n/**\n * What a Responses Object key names. OpenAPI defines four kinds of key:\n * `default`; an HTTP status code, exactly three digits in 100–599; a range,\n * `1XX`–`5XX` in either case; and an `x-` specification extension. The\n * whole key decides, never a numeric prefix: `6XX`, `4XXX`, `20X`, `600`,\n * `099` and `200 ` are `unrecognized`, like `error` or `Default`.\n */\nexport type ResponseKey =\n  | { kind: 'status'; code: number }\n  | { kind: 'range'; range: StatusRange }\n  | { kind: 'default' }\n  | { kind: 'extension' }\n  | { kind: 'unrecognized' };\n\n/**\n * Classify a Responses Object key. Every reader of a Responses Object —\n * an operation's responses, the const prefixes it reserves, a webhook's\n * responses — goes through here, so a key is a status code in one place or\n * in none.\n */\nexport function classifyResponseKey(key: string): ResponseKey {\n  if (key === 'default') return { kind: 'default' };\n  if (key.startsWith('x-')) return { kind: 'extension' };\n  if (/^[1-5]\\d{2}$/.test(key)) return { kind: 'status', code: Number(key) };\n  if (/^[1-5]XX$/i.test(key)) return { kind: 'range', range: key.toUpperCase() as StatusRange };\n  return { kind: 'unrecognized' };\n}\n\n/**\n * Warn about a Responses Object key OpenAPI does not define, which the\n * caller then ignores rather than drops silently. `label` names the\n * operation or webhook the key sits on.\n */\nexport function warnUnrecognizedResponseKey(key: string, label: string): void {\n  console.warn(\n    `[oagen] Warning: Ignoring response key \"${key}\" on ${label}: not a status code (three digits, 100–599), a 1XX–5XX range, or \"default\"`,\n  );\n}\n\nexport function classifyAndExtractResponse(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  options: ResponseClassificationOptions = {},\n): ResponseExtractionResult {\n  const body = classifyBody(schema, contextName, componentSchemas, options);\n  // Under an explicit `dataPath`, a body that was not unwrapped on that path\n  // is the wrapper the override iterates — a `$ref` to a component, an\n  // envelope detection would unwrap on another array, an inline body\n  // detection did not recognize — and its stop field is read here, once for\n  // every such shape, keyed by the path. A path that restates the one the\n  // envelope was unwrapped on (`isPaginated`) has had it read by\n  // `extractListResponse`; under `paginationDisabled` there is no iterator\n  // to stop.\n  const override = options.dataPathOverride;\n  if (override === undefined || options.paginationDisabled || body.isPaginated) return body;\n  const endOfIteration = bodyEndOfIteration(schema, override, componentSchemas);\n  return endOfIteration ? { ...body, endOfIteration } : body;\n}\n\n/**\n * The field that ends an iteration of a body kept as a wrapper under an\n * explicit `dataPath`, read beside the array the path names — the one\n * reader for every kept wrapper, whatever wraps it. The wrapper's\n * properties are collected exactly as a recognized envelope's are\n * (`collectObjectProperties`, which reads the body and every `allOf`\n * member, however deep, through `resolveBareSchema` — the resolver the path\n * walk uses — so a `$ref` body, a nullable wrapper around the body or\n * around any member, and a `$ref` chain to one all reach the same object\n * the path walked), and `detectEndOfIteration` reads them as it reads an\n * unwrapped envelope's: the fields beside the array the path names first,\n * under a parent of any name (`result.total_pages` next to `result.items`),\n * then the top level, then the metadata companions, and never the array\n * itself. `undefined` when nothing recognizable is declared, or the body\n * resolves to no object at all.\n */\nfunction bodyEndOfIteration(\n  schema: SchemaObject,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationEndOfIteration | undefined {\n  const { properties } = collectObjectProperties(schema, componentSchemas);\n  return detectEndOfIteration(properties, dataPath, componentSchemas);\n}\n\n/**\n * Why an explicit `endOfIteration` cannot be read from `schema`, or\n * `undefined` when it can: the override's counterpart of\n * `bodyEndOfIteration`, over the very property map that reader collects\n * (`collectObjectProperties`), so a field detection would read is one an\n * override may name and a field it would not see is not there for an\n * override either; `endOfIterationProblem` then walks the path and tests\n * the type. `schema` is the body as written — a `$ref`, an `allOf`, a\n * nullable wrapper — or `undefined` when the operation declares no body,\n * which no path resolves in.\n */\nexport function bodyEndOfIterationProblem(\n  end: PaginationEndOfIteration,\n  schema: SchemaObject | undefined,\n  componentSchemas?: Record<string, SchemaObject>,\n): string | undefined {\n  const properties = schema && collectObjectProperties(schema, componentSchemas).properties;\n  return endOfIterationProblem(end, properties, componentSchemas);\n}\n\n/**\n * Classify one body: a `$ref` names its component; an inline body is a list\n * envelope — unwrapped on its data array, unless an explicit `dataPath`\n * names another array in it — a single-resource wrapper, or a plain model.\n */\nfunction classifyBody(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  options: ResponseClassificationOptions,\n): ResponseExtractionResult {\n  // 1. If schema is a $ref, resolve to model name (Phase 1)\n  if (schema.$ref) {\n    return { response: schemaToTypeRef(schema, contextName), inlineModels: [], isPaginated: false };\n  }\n\n  // `properties` written beside a typing `allOf`/`oneOf`/`anyOf` are folded\n  // into the composition, as `schemaToTypeRef` and the field extractor read\n  // them (`foldSiblingProperties`), so a body is read the one way wherever it\n  // appears: the branches below read `properties` before a composition and\n  // would otherwise drop the composition that a field keeps. The variants\n  // that cannot take the properties are reported on the body as written,\n  // under the body's name, since the fold leaves `schemaToTypeRef` nothing\n  // to report.\n  warnOnUncarriedProperties(schema, contextName, undefined);\n  schema = foldSiblingProperties(schema);\n\n  // 2. Check for list envelope (structural detection: array prop + non-array companion)\n  const envelope = detectListEnvelope(schema);\n  if (envelope.isEnvelope) {\n    const override = options.dataPathOverride;\n    if (!options.paginationDisabled && (override === undefined || override === envelope.dataPath)) {\n      return extractListResponse(schema, contextName, envelope.dataPath!, componentSchemas, options.settle);\n    }\n    // A recognized envelope that is not unwrapped is kept as the wire shape,\n    // one model carrying every field, whichever reason keeps it: nothing\n    // pages the operation (`paginationDisabled` — `strategy: 'none'`, or no\n    // declared query parameter and no usable override), or an explicit\n    // `dataPath` names another array than the one it would be unwrapped on\n    // (detection was wrong for this operation; its stop field is read by the\n    // caller, `bodyEndOfIteration`). It never takes the single-resource\n    // reading below: an envelope with one required companion carrying a\n    // constant `type`/`object` (`{ data, pagination: { type: 'pagination',\n    // total } }` with `required: ['pagination']`) fits that shape, and\n    // unwrapping it would make the companion the whole response and drop\n    // `data`. `unpagedEnvelope` tells the caller which reason kept it, so an\n    // envelope kept for want of a paging parameter is warned about.\n    const kept = extractDirectResource(schema, contextName, componentSchemas, options.settle);\n    return options.paginationDisabled ? { ...kept, unpagedEnvelope: true } : kept;\n  }\n\n  // 3. Check for single-resource wrapper ({ resource_name: { object: \"...\", ... } })\n  if (isSingleResourceWrapper(schema)) {\n    return extractWrappedResource(schema, contextName, componentSchemas);\n  }\n\n  // 4. Direct resource or plain inline object\n  return extractDirectResource(schema, contextName, componentSchemas, options.settle);\n}\n\ninterface ListEnvelopeResult {\n  isEnvelope: boolean;\n  dataPath: string | null;\n}\n\nconst KNOWN_DATA_PATHS = new Set(['data', 'items', 'results', 'records', 'entries', 'values', 'nodes', 'edges']);\n\nfunction detectListEnvelope(schema: SchemaObject): ListEnvelopeResult {\n  // Collect all property sources (allOf sub-schemas or flat schema)\n  const propSources: Record<string, SchemaObject | undefined>[] = [];\n  if (schema.allOf) {\n    for (const sub of schema.allOf) {\n      if (sub.properties) propSources.push(sub.properties);\n    }\n  }\n  if (schema.properties) {\n    propSources.push(schema.properties);\n  }\n\n  if (propSources.length === 0) return { isEnvelope: false, dataPath: null };\n\n  // Merge all properties into a single view. A name two members declare is\n  // settled as every `allOf` merge settles it (`combineDeclarations`): the\n  // first declaration that declares a type, a typeless one only annotating\n  // it, so `data: { type: 'array' }` beside a later `data: { description }`\n  // is still the array detection looks for.\n  const mergedProps: Record<string, SchemaObject> = {};\n  for (const source of propSources) {\n    for (const [key, prop] of Object.entries(source)) {\n      if (!prop) continue;\n      const existing = mergedProps[key];\n      mergedProps[key] = existing ? combineDeclarations(existing, prop) : prop;\n    }\n  }\n\n  // Find array properties — typed, `items` with no `type`, or either under a\n  // nullable wrapper of any spelling (`arraySchemaOf`), or a `$ref` to an\n  // array component under such a wrapper (`isArrayComponentRef`), which\n  // `schemaToTypeRef` types as the array the component declares — and\n  // non-array companion properties\n  const arrayProps: string[] = [];\n  const nonArrayKeys: string[] = [];\n\n  for (const [key, propSchema] of Object.entries(mergedProps)) {\n    if (!propSchema) continue;\n    if (arraySchemaOf(propSchema) || isArrayComponentRef(propSchema)) {\n      arrayProps.push(key);\n    } else {\n      nonArrayKeys.push(key);\n    }\n  }\n\n  // List envelope heuristic: exactly one array property + at least one non-array companion\n  // that looks like pagination metadata.  A `data` array alone (e.g. with only an\n  // `object` discriminant companion) is NOT sufficient — the companion must indicate\n  // actual pagination (cursor, metadata, total, etc.).\n  if (arrayProps.length === 1 && nonArrayKeys.length >= 1) {\n    const arrayPropName = arrayProps[0];\n\n    // A companion is pagination metadata when it is one of the stop fields\n    // the end-of-iteration detector reads (`hasMore`, `hasNext`, `pageCount`,\n    // …) — one shared list, so an envelope that carries a stop field is\n    // always recognized — or when its name, read in any spelling, contains\n    // one of the metadata patterns (`meta`, `pagination`, `cursor`, …:\n    // `looksLikePaginationMetadata`, the recognizer the nested stop-field\n    // scan shares, so `pageInfo` marks an envelope exactly as `page_info`\n    // does and `pageInfo.hasNextPage` is then read as its stop field).\n    const hasPaginationCompanion = nonArrayKeys.some(\n      (key) => END_OF_ITERATION_FIELDS.includes(key) || looksLikePaginationMetadata(key),\n    );\n\n    if (KNOWN_DATA_PATHS.has(arrayPropName) && hasPaginationCompanion) {\n      return { isEnvelope: true, dataPath: arrayPropName };\n    }\n\n    // Non-standard array property name — still treat as envelope if pagination companion exists\n    if (hasPaginationCompanion) {\n      return { isEnvelope: true, dataPath: arrayPropName };\n    }\n  }\n\n  return { isEnvelope: false, dataPath: null };\n}\n\nfunction extractListResponse(\n  schema: SchemaObject,\n  contextName: string,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): ResponseExtractionResult {\n  let itemTypeRef: TypeRef = { kind: 'primitive', type: 'string' };\n  const inlineModels: Model[] = [];\n\n  const { properties, required } = collectObjectProperties(schema, componentSchemas);\n\n  const dataProp = properties[dataPath];\n  // The property's own text, as `buildFieldFromSchema` keeps it for every\n  // companion beside it; an item schema's description belongs to the item.\n  const dataDescription = dataProp?.description;\n  // The data array's type when it is a `$ref` to an array component: the\n  // array the component declares, with the component's own nullability.\n  let dataType: TypeRef | undefined;\n  if (dataProp && isArrayComponentRef(dataProp)) {\n    // A `$ref` to an array component, under any nullable wrapper, is the\n    // array the component declares, its items named under the component\n    // (`<Component>Item…`) and already materialized by the component pass —\n    // nothing is minted here, and `<Operation>Item` stays free.\n    dataType = schemaToTypeRef(dataProp, contextName);\n    const array = dataType.kind === 'nullable' ? dataType.inner : dataType;\n    if (array.kind === 'array') itemTypeRef = array.items;\n  } else {\n    // The array under whatever nullable wrapper the data property wears\n    // (`arraySchemaOf`); its items, whatever their shape, are typed and\n    // materialized as `<Operation>Item` (`typeInlineItems`).\n    const dataArray = dataProp ? arraySchemaOf(dataProp) : undefined;\n    if (dataArray?.items) {\n      const typed = typeInlineItems(\n        dataArray.items,\n        contextName.replace(/Response$/, '') + 'Item',\n        componentSchemas,\n        settle,\n      );\n      itemTypeRef = typed.itemType;\n      inlineModels.push(...typed.inlineModels);\n    }\n  }\n\n  // Everything the envelope carries besides the data array: the pagination\n  // companion (`list_metadata`, `pagination`, `has_more`, …) and any\n  // discriminant such as `object: \"list\"`. Without these an emitter cannot\n  // type the endpoint's actual response or read the next-page details.\n  const { envelopeFields, envelopeCompanions } = extractEnvelopeCompanions(\n    properties,\n    required,\n    dataPath,\n    contextName.replace(/Response$/, ''),\n    componentSchemas,\n  );\n\n  // The field that says the list is exhausted — `has_more`, `total_pages`,\n  // `pagination.totalPages` — so an iterator can stop without a wasted\n  // request: the read `bodyEndOfIteration` makes for a kept wrapper, on the\n  // properties already collected above.\n  const endOfIteration = detectEndOfIteration(properties, dataPath, componentSchemas);\n\n  return {\n    // The data array's own nullability is the response's: a `data` declared\n    // `type: ['array', 'null']`, OAS 3.0 `nullable: true`, or `oneOf`/`anyOf`\n    // with a `null` variant means the list the SDK returns may be null, so\n    // the wrapper `schemaToTypeRef` would give the field stays on `response`\n    // — `envelopeFields` leaves `data` out, so nothing else records it —\n    // while `itemType` is still what an iterator yields (`paginatedItemType`\n    // unwraps the same wrapper). A `$ref` to an array component carries the\n    // component's own nullability, and its wrapper's, the same way.\n    response:\n      dataType ??\n      (dataProp ? nullableIf(dataProp, { kind: 'array', items: itemTypeRef }) : { kind: 'array', items: itemTypeRef }),\n    inlineModels,\n    isPaginated: true,\n    dataPath,\n    ...(dataDescription !== undefined && { dataDescription }),\n    itemType: itemTypeRef,\n    envelopeFields,\n    endOfIteration,\n    envelopeCompanions: envelopeCompanions.length > 0 ? envelopeCompanions : undefined,\n  };\n}\n\n/**\n * Element type of the array an explicit `dataPath` points at, read from the\n * response document when the IR cannot answer — a `$ref` wrapper whose path\n * runs through a model the parser has not materialized (an array\n * component's, say), or an envelope the parser did not recognize — and the\n * check `extractResponses` makes before classifying a body, to learn whether\n * the path reaches an array at all. `undefined` when it does not.\n *\n * The array may sit under a nullable wrapper of any form — `type: ['array',\n * 'null']`, OAS 3.0 `nullable: true`, `oneOf: [{ type: 'array' }, { type:\n * 'null' }]`, a nullable `$ref` to an array component — which\n * `resolveBareSchema` looks through exactly as the IR walk\n * (`resolveDataPathItemType`) looks through the `nullable` TypeRef those\n * forms become, so the two never disagree about whether the path lands on\n * an array; `isArraySchema` then decides, as every other site does.\n *\n * The items are typed and materialized as every array response's are\n * (`typeInlineItems`): as a field named for the path (`result.items` →\n * `ListPetsResultItem`, `records` → `ListPetsRecord`; see\n * `inlineItemNameForPath`) under no parent — so the item type never names a\n * model nobody created.\n */\nexport function resolveDataPathFromSchema(\n  schema: SchemaObject,\n  dataPath: string,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): { itemType: TypeRef; inlineModels: Model[] } | undefined {\n  const target = resolveSchemaPath(schema, dataPath, componentSchemas);\n  if (!target) return undefined;\n  const array = resolveBareSchema(target, componentSchemas);\n  if (!isArraySchema(array) || !array.items) return undefined;\n  return typeInlineItems(array.items, inlineItemNameForPath(contextName, dataPath), componentSchemas, settle);\n}\n\n/**\n * Type an array's items and materialize every model they reference, as a\n * field named `itemName` under no parent: `schemaToTypeRef` names the\n * reference and `extractInlineModelsFromProperties` builds the models, and\n * the two mirror each other form for form, so the item type never names a\n * model nobody created. The one path for the items of an array response\n * body, a list envelope's data array and an explicit `dataPath`'s array,\n * whatever shape the items take. A `$ref` is a reference and mints nothing;\n * a plain object is that model (`ListPetsItem`); a nullable object\n * (`type: ['object', 'null']`, OAS 3.0 `nullable: true`, a nullable\n * `oneOf`) is a `nullable` reference to it; an inline enum is\n * `<itemName>`; the inline object variants of a union take the union's\n * names (`ListPetsItem`, `ListPetsItemWithSide`); an object that also\n * composes — `properties` beside an `allOf` or `oneOf` — is the\n * composition carrying the properties (`foldSiblingProperties`); the\n * objects of a nested array or map, and whatever any of these reference in\n * turn, are materialized under the name the reference uses.\n *\n * With `settle`, the names are settled against the spec-wide registry\n * through `materializeInlineSchema`, the one retry loop every deferred\n * schema goes through: the items are tried as `<Op>Item`, and when a name\n * they mint — the root, a union variant, a nested object — belongs to\n * another shape (a component model or enum, a component's field model, an\n * earlier operation's model), as `<Op>ResponseItem`, then `<Op>Item2`,\n * `<Op>Item3`, …, the first candidate that clashes with nothing; a shape\n * identical to a name's owner shares it and mints nothing, so items matching\n * a component `ListPetsItem` reference the component. The models minted are\n * recorded under the operation; a reference written by sharing another\n * site's model joins that site (`attachSharedRefs`), so a later rename of\n * the shared model — a deprecated copy named like a live one — reaches this\n * array too. Without `settle` — a dry run that only reads names, a direct\n * call — the items take `<Op>Item` as written.\n */\nfunction typeInlineItems(\n  items: SchemaObject,\n  itemName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): { itemType: TypeRef; inlineModels: Model[] } {\n  const inlineModels: Model[] = [];\n  if (settle) {\n    const itemType = materializeInlineSchema(items, {\n      stem: (index) =>\n        index === 0 ? itemName : index === 1 ? itemName.replace(/Item$/, 'ResponseItem') : `${itemName}${index}`,\n      componentSchemas,\n      registry: settle.registry,\n      operation: settle.operation,\n      models: inlineModels,\n    });\n    return { itemType, inlineModels };\n  }\n  extractInlineModelsFromProperties({ properties: { [itemName]: items } }, inlineModels, undefined, componentSchemas);\n  return { itemType: schemaToTypeRef(items, itemName), inlineModels };\n}\n\n/**\n * Name for inline items reached through an overridden `dataPath`, built from\n * the path the way the inline extractor names a nested field's items: the\n * operation, the enclosing properties, then the singular of the array's own\n * name (`result.items` → `ListPetsResultItem`). It therefore coincides with a\n * model the parser may already have minted for that field, and never takes\n * the bare `<Op>Item` that a recognized envelope's data array owns.\n */\nfunction inlineItemNameForPath(contextName: string, dataPath: string): string {\n  const segments = dataPath.split('.');\n  const parents = segments\n    .slice(0, -1)\n    .map((segment) => toPascalCase(segment))\n    .join('');\n  const own = singularize(toPascalCase(segments[segments.length - 1]));\n  return contextName.replace(/Response$/, '') + parents + own;\n}\n\n/**\n * Type a list envelope's companion properties as fields, lifting any inline\n * object among them (and anything nested inside it) to a model.\n *\n * Models come from `extractInlineModelsFromProperties`, the extractor that\n * mirrors `schemaToTypeRef` form for form — plain, nullable and `allOf`\n * objects, arrays of objects, and every `oneOf`/`anyOf` object variant — so a\n * field's reference always has a model behind it.\n *\n * Each companion is extracted twice: once under the operation's name, which\n * is how its models enter the IR (`ListUsersListMetadata`), and once under no\n * parent, which yields the name each model would carry if named from its\n * property alone (`ListMetadata`). Both runs walk the same code path, so the\n * two model lists line up index for index. `resolveEnvelopeCompanionNames`\n * later picks, per companion, which of the two names survives — the bare one\n * only where every copy of that companion across the API agrees structurally.\n */\nfunction extractEnvelopeCompanions(\n  properties: Record<string, SchemaObject>,\n  required: string[],\n  dataPath: string,\n  operationName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): { envelopeFields: Field[]; envelopeCompanions: EnvelopeCompanion[] } {\n  const envelopeFields: Field[] = [];\n  const envelopeCompanions: EnvelopeCompanion[] = [];\n  const requiredSet = new Set(required);\n  // The companion is extracted from a one-property schema, so hand the\n  // extractor the envelope's full property list: array items and map values\n  // must step aside from a singular sibling exactly as the field does.\n  const siblings = collectProperties({ properties });\n\n  for (const [key, propSchema] of Object.entries(properties)) {\n    if (key === dataPath) continue;\n    const field = buildFieldFromSchema(key, propSchema, operationName, requiredSet, componentSchemas, siblings);\n    envelopeFields.push(field);\n\n    // Both runs get the component map so a companion's `$ref` fields carry\n    // the component's example in the qualified and bare copies alike; it\n    // only feeds field metadata, so the two model lists still line up.\n    const single: SchemaObject = { type: 'object', properties: { [key]: propSchema } };\n    const models: Model[] = [];\n    extractInlineModelsFromProperties(single, models, operationName, componentSchemas, siblings);\n    if (models.length === 0) continue;\n    const bare: Model[] = [];\n    extractInlineModelsFromProperties(single, bare, undefined, componentSchemas, siblings);\n    envelopeCompanions.push({ field, models, bareNames: bare.map((m) => m.name) });\n  }\n\n  return { envelopeFields, envelopeCompanions };\n}\n\nfunction hasDiscriminantConstField(schema: SchemaObject): { property: string; value: string } | null {\n  if (!schema.properties) return null;\n\n  // Prefer well-known discriminant properties for backward compatibility\n  const preferred = ['object', 'type'];\n  for (const name of preferred) {\n    const field = schema.properties[name];\n    if (!field) continue;\n    if (field.const !== undefined && typeof field.const === 'string') {\n      return { property: name, value: field.const };\n    }\n    if (field.enum && field.enum.length === 1 && typeof field.enum[0] === 'string') {\n      return { property: name, value: field.enum[0] };\n    }\n  }\n\n  // Fall back to any property with a const or single-value enum\n  for (const [name, field] of Object.entries(schema.properties)) {\n    if (!field) continue;\n    if (field.const !== undefined && typeof field.const === 'string') {\n      return { property: name, value: field.const };\n    }\n    if (field.enum && field.enum.length === 1 && typeof field.enum[0] === 'string') {\n      return { property: name, value: field.enum[0] };\n    }\n  }\n\n  return null;\n}\n\nfunction isSingleResourceWrapper(schema: SchemaObject): boolean {\n  if (schema.type !== 'object') return false;\n  if (!schema.properties) return false;\n\n  // Find the wrapper property: use required[0] if available, or the single property key\n  let wrapperKey: string | undefined;\n  if (schema.required && schema.required.length === 1) {\n    wrapperKey = schema.required[0];\n  } else {\n    const propKeys = Object.keys(schema.properties);\n    if (propKeys.length === 1) {\n      wrapperKey = propKeys[0];\n    }\n  }\n  if (!wrapperKey) return false;\n\n  const propSchema = schema.properties[wrapperKey];\n  if (!propSchema) return false;\n\n  // Direct object with a discriminant const field\n  if (propSchema.type === 'object' && hasDiscriminantConstField(propSchema) !== null) return true;\n\n  // oneOf with object + null (nullable resource)\n  if (propSchema.oneOf) {\n    return propSchema.oneOf.some((v) => v.type === 'object' && hasDiscriminantConstField(v) !== null);\n  }\n\n  return false;\n}\n\nfunction extractWrappedResource(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): ResponseExtractionResult {\n  const props = schema.properties!;\n  const wrapperKey = schema.required && schema.required.length === 1 ? schema.required[0] : Object.keys(props)[0];\n  const propSchema = props[wrapperKey]!;\n  const inlineModels: Model[] = [];\n\n  // Derive model name from the object const value or wrapper property name\n  const resourceName = contextName.replace(/Response$/, '');\n\n  if (propSchema.oneOf) {\n    const objectVariant = propSchema.oneOf.find((v) => v.type === 'object' && hasDiscriminantConstField(v) !== null);\n\n    if (objectVariant) {\n      const modelName = deriveModelName(objectVariant, resourceName);\n      // `oneOf: [object, null]` is a nullable wrapper: the model built from\n      // its one branch takes the wrapper's `deprecated` and limits, as every\n      // other nullable unwrap gives it (`collapsedNullableBranch`); a\n      // multi-variant union's variant is built as written.\n      const source = collapsedNullableBranch(propSchema) ?? objectVariant;\n      inlineModels.push(...extractInlineModel(modelName, source, componentSchemas));\n\n      const hasNullVariant = propSchema.oneOf.some(\n        (v) => v.type === 'null' || (Array.isArray(v.type) && v.type.includes('null')),\n      );\n\n      const modelRef: TypeRef = { kind: 'model', name: modelName };\n      return {\n        response: hasNullVariant ? { kind: 'nullable', inner: modelRef } : modelRef,\n        inlineModels,\n        isPaginated: false,\n      };\n    }\n  }\n\n  // Direct object\n  const modelName = deriveModelName(propSchema, resourceName);\n  inlineModels.push(...extractInlineModel(modelName, propSchema, componentSchemas));\n\n  return {\n    response: { kind: 'model', name: modelName },\n    inlineModels,\n    isPaginated: false,\n  };\n}\n\n/**\n * How `extractDirectResource` reads a body that is no `$ref`, list envelope\n * or single-resource wrapper — the one dispatch it branches on and\n * `bodyTypesAsUnknown` predicts by, so a shape is read one way by both:\n * an object declaring properties of its own (`type: 'object'` or none;\n * `composedWithoutFields` leaves an empty `properties: {}` beside a\n * composition to the composition); an `allOf` that types the schema\n * (`classifyInlineSchema`), read as `readInlineAllOf` reads it — a\n * `reference`, a lone `unwrapped` member carried with the wrapper's limits,\n * flag and link (`unwrappedAllOfMember`), or a `merged` model; an array\n * with items under a nullable wrapper of any spelling, a single-entry type\n * list included (`arraySchemaOf`: `type: ['array']` is an array here as\n * `isArraySchema` reads it); and otherwise `typeRef`, typed by\n * `schemaToTypeRef` — a union, a primitive, a map, or `unknown`.\n */\ntype DirectResourceReading =\n  | { kind: 'object' }\n  | { kind: 'reference' }\n  | { kind: 'unwrapped'; member: SchemaObject }\n  | { kind: 'merged' }\n  | { kind: 'array'; items: SchemaObject }\n  | { kind: 'typeRef' };\n\nfunction directResourceReading(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): DirectResourceReading {\n  if (schema.properties && !composedWithoutFields(schema) && (schema.type === 'object' || !schema.type)) {\n    return { kind: 'object' };\n  }\n  if (schema.allOf && classifyInlineSchema(schema) === 'allOf') {\n    const reading = readInlineAllOf(schema.allOf, schema, componentSchemas);\n    if (reading === 'reference') return { kind: 'reference' };\n    if (reading === 'unwrapped') return { kind: 'unwrapped', member: unwrappedAllOfMember(schema, schema.allOf[0]!) };\n    return { kind: 'merged' };\n  }\n  const array = arraySchemaOf(schema);\n  if (array?.items) return { kind: 'array', items: array.items };\n  return { kind: 'typeRef' };\n}\n\n/**\n * Whether classification types a body as the bare `unknown` — the reading\n * `classifyAndExtractResponse` makes, without making it: a `$ref` is a\n * reference; the body is folded as classification folds it\n * (`foldSiblingProperties`, without the warning it then issues); a list\n * envelope and a single-resource wrapper are typed; and what is left takes\n * `extractDirectResource`'s own dispatch (`directResourceReading`): an\n * object, an `allOf` read as a reference or a merge, and an array are\n * typed, a lone `allOf` member is read as the member exactly as\n * `extractDirectResource` recurses into it, and a `typeRef` reading is\n * typed by `schemaToTypeRef` and is `unknown` exactly when `typesAsUnknown`\n * holds. The one answer a reader that must know before any body is read\n * asks (`bodyIsTyped`, choosing the primary response), so no shape is typed\n * by classification and unknown to it, or the reverse — `type: ['array']`\n * with items is an array to both.\n */\nexport function bodyTypesAsUnknown(schema: SchemaObject, componentSchemas?: Record<string, SchemaObject>): boolean {\n  if (schema.$ref) return false;\n  const folded = foldSiblingProperties(schema);\n  if (detectListEnvelope(folded).isEnvelope || isSingleResourceWrapper(folded)) return false;\n  return directResourceTypesAsUnknown(folded, componentSchemas);\n}\n\n/** `bodyTypesAsUnknown` from `extractDirectResource`'s dispatch on, where its recursion into a lone `allOf` member lands. */\nfunction directResourceTypesAsUnknown(schema: SchemaObject, componentSchemas?: Record<string, SchemaObject>): boolean {\n  const reading = directResourceReading(schema, componentSchemas);\n  if (reading.kind === 'unwrapped') return directResourceTypesAsUnknown(reading.member, componentSchemas);\n  return reading.kind === 'typeRef' && typesAsUnknown(schema);\n}\n\n/**\n * `wrapper` is the single-member `allOf` wrapper the body was unwrapped\n * from, when it was (the `'unwrapped'` reading below): the schema the\n * document wrote for the body, whose `description` and link the type built\n * from the member takes, as `schemaToTypeRef` gives the same wrapper on a\n * field or a parameter (`withWrapperDocs`). It reaches only the one site\n * that types the member itself, the fall-through at the end, so an inline\n * enum body under the wrapper lifts with the wrapper's text; a model built\n * from an object member keeps the member's own `description`, as a field's\n * does. Through nested wrappers the outermost text wins, then the next, then\n * the member's own: each level composes its own wrapper with the one handed\n * down before passing it on.\n */\nfunction extractDirectResource(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n  wrapper?: SchemaObject,\n): ResponseExtractionResult {\n  const inlineModels: Model[] = [];\n  const reading = directResourceReading(schema, componentSchemas);\n\n  // Direct object with properties (with or without explicit type: 'object').\n  // An empty `properties: {}` beside a composition that types the schema is\n  // not the body's object — the fold leaves it as written\n  // (`hasFoldableProperties`) and the `allOf` or `oneOf` branch below reads\n  // it, as `{ allOf: [Pet] }` alone is read — so a body declaring no field of\n  // its own never becomes an empty model that drops the composition.\n  if (reading.kind === 'object') {\n    const modelName = deriveModelName(schema, contextName);\n    inlineModels.push(...extractInlineModel(modelName, schema, componentSchemas));\n    return {\n      response: { kind: 'model', name: modelName },\n      inlineModels,\n      isPaginated: false,\n    };\n  }\n\n  // allOf — read the one way every site reads an inline `allOf`\n  // (`readInlineAllOf`), when the `allOf` is what types the body\n  // (`classifyInlineSchema`; an `allOf` of bare limits leaves the body to\n  // its own keywords below). A single `$ref` member with nothing beside it\n  // that adds to the component is that component, and nothing is minted —\n  // as a field of the same schema is typed (workos/oagen#307: the body was\n  // a copy of the component under its own name); a ref no component answers\n  // is that reference too. A second `$ref`, or a `required` beside the\n  // `$ref`, makes the body the merge below, as it makes a field (every\n  // component's properties and every `required` kept). A lone member with\n  // nothing added to it is the body itself, carrying the wrapper's limits,\n  // flag and link (`unwrappedAllOfMember`), read by the branches of this\n  // function as if written in its place, and the type built from it takes\n  // the wrapper's text and link too (`wrapper`, see above); a `required`\n  // beside a lone object member makes the body the merge too, so `name`\n  // stays required. Every other\n  // `allOf` is merged into a single model through `mergeAllOfMembers`: $ref\n  // branches are resolved against component schemas so the referenced\n  // model's fields are merged rather than silently dropped, and the inline\n  // object variants of a `oneOf`/`anyOf` member contribute their fields as\n  // optional ones (workos/oagen#283), as the same schema's component model\n  // has them. Earlier members win on a shared name there, and the fold\n  // places the body's own properties first, so an own `kind` enum beside a\n  // member's plain `kind` stays the enum here as it does in a field or an\n  // array's items.\n  if (reading.kind === 'reference') {\n    return { response: schemaToTypeRef(schema, contextName), inlineModels, isPaginated: false };\n  }\n  if (reading.kind === 'unwrapped') {\n    const outer = wrapper ? withWrapperDocs(schema, wrapper) : schema;\n    return extractDirectResource(reading.member, contextName, componentSchemas, settle, outer);\n  }\n  if (reading.kind === 'merged') {\n    const merged = mergeAllOfMembers(schema, componentSchemas);\n    const mergedRefFields = merged.resolvedRefs.length > 0;\n\n    // An unresolvable $ref branch (no component schema map) would drop the\n    // referenced model's fields entirely — prefer the referenced model as\n    // the response type over a merge that silently guts it.\n    if (merged.unresolvedRefs.length === 1 && !mergedRefFields) {\n      return {\n        response: schemaToTypeRef({ $ref: merged.unresolvedRefs[0] }, contextName),\n        inlineModels,\n        isPaginated: false,\n      };\n    }\n\n    if (merged.properties.length > 0) {\n      // The rebuilt schema carries the wrapper's limits, conjoined with its\n      // inline members', so it still declares what an instance must satisfy,\n      // the wrapper's own link and its own `deprecated` flag, as a component\n      // `allOf` model carries them; a member's stay on that member (a `$ref`\n      // member's on its component).\n      const rebuilt = mergedObjectSchema(merged);\n      // Fields merged from a $ref carry the referenced model's const\n      // discriminant (e.g. object: 'magic_auth'); deriving the name from it\n      // would collide with the component model, so keep the context name.\n      const modelName = mergedRefFields ? toPascalCase(contextName) : deriveModelName(rebuilt, contextName);\n      inlineModels.push(...extractInlineModel(modelName, rebuilt, componentSchemas));\n      return {\n        response: { kind: 'model', name: modelName },\n        inlineModels,\n        isPaginated: false,\n      };\n    }\n  }\n\n  // Array — `type: 'array'` or, since JSON Schema does not require `type`\n  // beside `items`, bare `items`, under a nullable wrapper of any spelling\n  // (`type: ['array', 'null']`, OAS 3.0 `nullable: true`, `oneOf`/`anyOf`\n  // with a `null` variant, with or without `items` beside it) or none:\n  // `arraySchemaOf`, which unwraps as `schemaToTypeRef` does and then asks\n  // `isArraySchema`, the one test every site makes. The items, whatever\n  // their shape, are typed and materialized as `<Operation>Item` under no\n  // parent (`typeInlineItems`) — a `$ref` stays the reference, a plain\n  // object is `<Operation>Item`, a union's inline object variants take the\n  // union's names from it — with the nullable wrapper `schemaToTypeRef`\n  // would give the array. Read before the `oneOf` branch below, which\n  // would otherwise materialize a nullable array's items a second time\n  // under the response's own name.\n  if (reading.kind === 'array') {\n    const typed = typeInlineItems(\n      reading.items,\n      contextName.replace(/Response$/, '') + 'Item',\n      componentSchemas,\n      settle,\n    );\n    return {\n      response: nullableIf(schema, { kind: 'array', items: typed.itemType }),\n      inlineModels: [...inlineModels, ...typed.inlineModels],\n      isPaginated: false,\n    };\n  }\n\n  // oneOf — delegate to schemaToTypeRef (returns union) and materialize the\n  // inline object variants through the field extractor, as a field of this\n  // name under no parent: it names them exactly as the union below references\n  // them (`nameInlineVariants` from the context name — `GetThingResponse`,\n  // `GetThingResponseWithSide`, `SquareGetThingResponse`), covers a nullable\n  // (`type: ['object', 'null']`) or multi-type variant that a plain\n  // `type === 'object'` test would skip, and recurses into everything nested\n  // under each variant, so the response never references a model the parser\n  // did not create.\n  if (schema.oneOf) {\n    extractInlineModelsFromProperties(\n      { properties: { [contextName]: schema } },\n      inlineModels,\n      undefined,\n      componentSchemas,\n    );\n  }\n\n  // Anything else is typed by schemaToTypeRef (primitive, union, map, array\n  // of unions, nullable object, …). Such a TypeRef can still reach an inline\n  // model — a map whose values are an inline object (`additionalProperties`),\n  // an array whose items are a union of inline objects, a nullable\n  // `type: ['object', 'null']` object, a map of arrays of objects — so\n  // materialize them the way the oneOf branch does: as a field of this name\n  // under no parent, which names every nested model exactly as the TypeRef\n  // references it. The oneOf branch may already have pushed some of them, so\n  // dedupe by name.\n  const nested: Model[] = [];\n  extractInlineModelsFromProperties({ properties: { [contextName]: schema } }, nested, undefined, componentSchemas);\n  const known = new Set(inlineModels.map((m) => m.name));\n  for (const model of nested) {\n    if (known.has(model.name)) continue;\n    known.add(model.name);\n    inlineModels.push(model);\n  }\n  // The one site that types the unwrapped member itself: it carries the\n  // wrapper's text and link, as the type builder gives the same wrapper on\n  // a field (`withWrapperDocs`), so an inline enum lifted here documents\n  // itself by the wrapper. The models materialized above are built from the\n  // member as written.\n  return {\n    response: schemaToTypeRef(wrapper ? withWrapperDocs(schema, wrapper) : schema, contextName),\n    inlineModels,\n    isPaginated: false,\n  };\n}\n\n/**\n * Whether `schema` writes an empty `properties: {}` beside an `allOf`,\n * `oneOf` or `anyOf` that types it (`classifyInlineSchema`). Such a schema\n * declares no field of its own, so the object branch of a body path must\n * not claim it: the composition is read instead, as it is when the\n * `properties` keyword is absent. Shared by the response and request-body\n * paths.\n */\nexport function composedWithoutFields(schema: SchemaObject): boolean {\n  if (!schema.properties || Object.keys(schema.properties).length > 0) return false;\n  const kind = classifyInlineSchema(schema);\n  return kind === 'allOf' || kind === 'union';\n}\n\n/**\n * Wrap `ref` in `nullable` when `schemaToTypeRef` would wrap the schema's\n * own type (`declaresNull`). For the places the response path builds an\n * array TypeRef itself instead of delegating.\n */\nfunction nullableIf(schema: SchemaObject, ref: TypeRef): TypeRef {\n  return declaresNull(schema) ? { kind: 'nullable', inner: ref } : ref;\n}\n\nfunction deriveModelName(schema: SchemaObject, fallback: string): string {\n  if (!schema.properties) return toPascalCase(fallback);\n  // A list envelope's const (`object: 'list'`) names the envelope's kind, which\n  // every envelope of the API shares, not what it lists (workos/oagen#418).\n  if (detectListEnvelope(schema).isEnvelope) return toPascalCase(fallback);\n\n  // Prefer well-known discriminant properties for backward compatibility\n  const preferred = ['object', 'type'];\n  for (const name of preferred) {\n    const field = schema.properties[name];\n    if (field && field.const && typeof field.const === 'string') {\n      return toPascalCase(field.const);\n    }\n  }\n\n  // Fall back to any property with a const string value\n  for (const [, field] of Object.entries(schema.properties)) {\n    if (field && field.const && typeof field.const === 'string') {\n      return toPascalCase(field.const);\n    }\n  }\n\n  return toPascalCase(fallback);\n}\n\n/**\n * Materialise an inline response object (and every nested inline object\n * under it) as models. `componentSchemas` only feeds `buildFieldFromSchema`,\n * so a response field that `$ref`s a component takes the component's\n * `example`/`examples` exactly as a request-body or component-model field\n * does; nested models get the same map so the fallback reaches every level.\n */\nfunction extractInlineModel(\n  name: string,\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): Model[] {\n  const requiredSet = new Set(schema.required ?? []);\n  const fields: Field[] = [];\n  const properties = schema.properties ?? {};\n  const nestedModels: Model[] = [];\n\n  const siblings = collectProperties(schema);\n  for (const [fieldName, fieldSchema] of Object.entries(properties)) {\n    if (!fieldSchema) continue;\n    fields.push(buildFieldFromSchema(fieldName, fieldSchema, name, requiredSet, componentSchemas, siblings));\n  }\n\n  // Every nested inline model a field references — an inline object, array\n  // items, map values, an `allOf` merge or `$ref` augmentation, every\n  // `oneOf`/`anyOf` variant (numbered, const-prefixed, nullable, multi-type,\n  // with `<Variant>Item` members), with sibling-aware item/value names —\n  // comes from the same extractor that materializes them for component\n  // schemas and request bodies. `buildFieldFromSchema` above named the\n  // references through `schemaToTypeRef`; this names the models the same way,\n  // so they agree by construction instead of through a response-local copy of\n  // the rules.\n  extractInlineModelsFromProperties(schema, nestedModels, name, componentSchemas);\n\n  return [\n    {\n      name,\n      description: schema.description,\n      ...externalDocsEntry(schema.externalDocs),\n      fields,\n      ...deprecatedEntry(schema),\n      ...constraintsEntry(schema),\n      ...schemaExtensionsEntry(schema),\n    },\n    ...nestedModels,\n  ];\n}\n","/**\n * Resolution of a Path Item written as a `$ref`.\n *\n * The bundler never inlines internal refs (`dereference: false`), so an entry\n * under `paths` or `webhooks` written as `{ $ref: '#/components/pathItems/Pets' }`\n * reaches extraction as a Reference Object with no operations, `parameters`,\n * `servers`, `summary` or `description` of its own. This module is\n * self-contained so both maps resolve the same way, through one function:\n * `extractOperations` resolves every `paths` entry before reading any of them\n * (issue #300), and `collectWebhookEntries` resolves each `webhooks` entry.\n */\n\n/** Where a path item is read from, for diagnostics. */\nexport interface PathItemSite {\n  /** `'path'` for an entry under `paths`, `'webhook'` for one under `webhooks`. */\n  kind: 'path' | 'webhook';\n  /** The entry's key: the path template (`/pets`) or the webhook name (`petAdopted`). */\n  key: string;\n}\n\n/**\n * The path item an entry denotes: the entry itself, or the\n * `components/pathItems` component a `$ref` chain leads to. Fields written\n * beside a `$ref` — on the entry or on a link of its chain — are not merged\n * in: OpenAPI leaves a field present on both sides undefined, and the\n * referenced item is taken whole so the rule does not depend on which fields\n * clash. They are reported once per entry, naming the site and the keys, so\n * a `post` written beside a ref to an item that declares only `get` is not\n * lost silently; an `x-` extension beside the `$ref` is not reported, since\n * the parser reads none off a path item. Returns `undefined`, after one\n * warning naming the site, for an entry that is not an object, a `$ref` that\n * is not a string, a ref outside `components/pathItems` (into another\n * section, or into another `paths` entry), a dangling ref, or a cycle; the\n * caller skips the entry. A dangling ref and a cycle are only reachable when\n * the document bypassed the bundler, which fails on either before parsing\n * (`Can't resolve $ref`; `Self-referencing circular pointer`).\n */\nexport function resolvePathItemRef(\n  raw: unknown,\n  componentPathItems: Record<string, Record<string, unknown>> | undefined,\n  site: PathItemSite,\n): Record<string, unknown> | undefined {\n  const label = `${site.kind === 'path' ? 'Path' : 'Webhook'} \"${site.key}\"`;\n  const seenRefs = new Set<string>();\n  /** Keys written beside a `$ref` along the chain, in document order; reported once the item is resolved. */\n  const droppedKeys: string[] = [];\n  let current: unknown = raw;\n  while (true) {\n    if (!isRecord(current)) {\n      console.warn(`[oagen] Warning: ${label} is not a path item object; skipping it.`);\n      return undefined;\n    }\n    const ref = current.$ref;\n    if (ref === undefined) {\n      if (droppedKeys.length > 0) {\n        console.warn(\n          `[oagen] Warning: ${label} has fields beside its $ref (${droppedKeys.map((key) => `\"${key}\"`).join(', ')}) ` +\n            'that are not read: the referenced path item is taken whole.',\n        );\n      }\n      return current;\n    }\n    if (typeof ref !== 'string') {\n      console.warn(`[oagen] Warning: ${label} has a non-string $ref; skipping it.`);\n      return undefined;\n    }\n    for (const key of Object.keys(current)) {\n      if (key !== '$ref' && !key.startsWith('x-') && !droppedKeys.includes(key)) droppedKeys.push(key);\n    }\n    if (seenRefs.has(ref)) {\n      console.warn(\n        `[oagen] Warning: Circular path item $ref chain starting at \"${ref}\" for ${site.kind} \"${site.key}\"; skipping it.`,\n      );\n      return undefined;\n    }\n    seenRefs.add(ref);\n    const resolved = resolveComponentRef(ref, 'pathItems', componentPathItems);\n    if (!resolved) {\n      console.warn(\n        `[oagen] Warning: Unresolved path item $ref \"${ref}\" for ${site.kind} \"${site.key}\": ` +\n          `no matching entry under components/pathItems. Skipping the ${site.kind}.`,\n      );\n      return undefined;\n    }\n    current = resolved;\n  }\n}\n\n/**\n * The component a `#/components/<section>/<name>` pointer names, or\n * `undefined` when it points anywhere else or at nothing. The whole pointer\n * is matched, so a ref into another section never resolves off a same-named\n * entry of this one. Shared by the path item resolution above and every\n * Reference Object resolver (`followReference` in `reference-objects.ts`).\n */\nexport function resolveComponentRef(\n  ref: string,\n  section: 'pathItems' | 'parameters' | 'requestBodies' | 'responses' | 'headers' | 'examples',\n  components: Record<string, Record<string, unknown>> | undefined,\n): Record<string, unknown> | undefined {\n  const prefix = `#/components/${section}/`;\n  if (!ref.startsWith(prefix)) return undefined;\n  // JSON Pointer escapes (RFC 6901 §4): `~1` -> `/`, then `~0` -> `~`, in that order.\n  const refName = ref.slice(prefix.length).replace(/~1/g, '/').replace(/~0/g, '~');\n  return refName === '' ? undefined : components?.[refName];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Resolution of Reference Objects: `{ $ref: '#/components/<section>/<name>' }`\n * written where OpenAPI allows one in place of a Parameter, Request Body,\n * Response, Header or Example Object. The bundler never inlines internal refs\n * (`dereference: false`), so each reaches the parser as written and is\n * followed here, through one walk, with one reading of the text written\n * beside the `$ref`.\n *\n * OAS 3.1 (§4.8.23) gives a Reference Object a `summary` and a `description`\n * that override the referenced component's; OAS 3.0 gives it no field but\n * `$ref`, so there anything written beside one is ignored\n * (`siblingDocsMode`). Each ref in a chain overrides what it points at, so\n * the outermost text with non-whitespace content wins over an inner ref's\n * and over the component's own; a blank sibling is no text and falls\n * through, as a blank `summary` on an operation falls through to its path\n * item's. `summary` is applied only where the referenced object type has one\n * — an Example Object; OpenAPI says it has no effect elsewhere — so a\n * Parameter, Request Body, Response or Header never gains a `summary` key\n * (`REFERENCE_DOC_FIELDS`).\n *\n * A Path Item's `$ref` is not a Reference Object: OpenAPI leaves a field\n * present on both sides undefined, and `resolvePathItemRef` takes the\n * referenced item whole. A Schema Object's `$ref` is JSON Schema's, whose\n * siblings the field extractor reads (`Field.description`).\n */\nimport { resolveComponentRef } from './path-item-refs.js';\n\n/** Whether text written beside a `$ref` overrides the referenced component's (OAS 3.1) or is ignored (OAS 3.0). */\nexport type SiblingDocs = 'override' | 'ignore';\n\n/** `'ignore'` for an OAS 3.0 document, where nothing beside a `$ref` is read; `'override'` for 3.1 and for a version not recognised. */\nexport function siblingDocsMode(openapiVersion: string | undefined): SiblingDocs {\n  return openapiVersion?.startsWith('3.0') ? 'ignore' : 'override';\n}\n\n/** The `components` sections a Reference Object may point into. */\nexport type ReferenceSection = 'parameters' | 'requestBodies' | 'responses' | 'headers' | 'examples';\n\n/** A Reference Object as written, with the documentation OAS 3.1 lets it carry beside the `$ref`. */\nexport interface ReferenceObject {\n  $ref: string;\n  summary?: string;\n  description?: string;\n}\n\ntype ReferenceDocField = 'summary' | 'description';\n\n/** The documentation a Reference Object overrides on each object type: `description` everywhere, `summary` only where the type has one. */\nconst REFERENCE_DOC_FIELDS: Record<ReferenceSection, readonly ReferenceDocField[]> = {\n  parameters: ['description'],\n  requestBodies: ['description'],\n  responses: ['description'],\n  headers: ['description'],\n  examples: ['summary', 'description'],\n};\n\n/**\n * How a walk ended: at the component (or at an inline object that was no\n * reference), at a ref already seen on the chain, at a ref nothing under the\n * section answers (a pointer into another section included, since the whole\n * pointer is matched), or at a `$ref` that is not a string.\n */\nexport type ReferenceOutcome = 'resolved' | 'circular' | 'unresolved' | 'malformed';\n\nexport interface FollowedReference<T> {\n  outcome: ReferenceOutcome;\n  /**\n   * The object the walk ended on, with the text kept from the refs along the\n   * chain applied over its own: the component for `resolved`, else the\n   * Reference Object the walk stopped at, as written. The object itself when\n   * nothing was kept, so an inline object or an undescribed ref keeps its\n   * identity. Typed as the caller expects; for a failure it is the ref.\n   */\n  value: T;\n  /** The `$ref` the walk stopped at, for a failure (`String()` of a malformed one); absent when resolved. */\n  ref?: string;\n}\n\n/**\n * Follow `raw` through `#/components/<section>/…` refs to the object it\n * denotes, keeping the text written beside each ref by the rule above, and\n * say how the walk ended. What a failure means — fail the parse, drop the\n * node, read the ref as written — is each caller's own; the walk itself\n * never reports. A `$ref` key holding `undefined` is no reference, and a\n * component that is not an object answers nothing.\n */\nexport function followReference<T extends object>(\n  raw: T | ReferenceObject,\n  section: ReferenceSection,\n  components: Record<string, Record<string, unknown>> | undefined,\n  siblings: SiblingDocs,\n): FollowedReference<T> {\n  const fields = REFERENCE_DOC_FIELDS[section];\n  const seen = new Set<string>();\n  const kept: Partial<Record<ReferenceDocField, string>> = {};\n  let current: object = raw;\n  const ended = (outcome: ReferenceOutcome, ref?: string): FollowedReference<T> => ({\n    outcome,\n    value: (Object.keys(kept).length === 0 ? current : { ...current, ...kept }) as T,\n    ...(ref !== undefined ? { ref } : {}),\n  });\n\n  while ('$ref' in current) {\n    const ref = (current as { $ref: unknown }).$ref;\n    if (ref === undefined) break;\n    if (typeof ref !== 'string') return ended('malformed', String(ref));\n    if (siblings === 'override') {\n      for (const field of fields) {\n        const text = (current as Partial<Record<ReferenceDocField, unknown>>)[field];\n        if (kept[field] === undefined && typeof text === 'string' && text.trim() !== '') kept[field] = text;\n      }\n    }\n    if (seen.has(ref)) return ended('circular', ref);\n    seen.add(ref);\n    const resolved = resolveComponentRef(ref, section, components);\n    if (!resolved || typeof resolved !== 'object') return ended('unresolved', ref);\n    current = resolved;\n  }\n  return ended('resolved');\n}\n","/**\n * Resolution of Reference Objects into `components/responses`.\n *\n * The bundler never inlines internal refs (`dereference: false`), so a\n * response written as `{ $ref: '#/components/responses/Problem' }` reaches\n * extraction as a Reference Object whose `headers` and `content` are\n * nowhere to be read. This module is self-contained so every response path\n * — fallback, explicit status code, webhook — can resolve the same way.\n */\n\nimport { followReference, type ReferenceObject, type SiblingDocs } from './reference-objects.js';\n\nexport type { ReferenceObject };\n\n/**\n * Resolve a raw response to a concrete Response Object, following `$ref`\n * chains into `components/responses` (`followReference`, the walk every\n * Reference Object takes). The text written beside a ref follows the one\n * rule stated there: in an OAS 3.1 document the outermost sibling\n * `description` with content wins over an inner ref's and over the\n * component's; under `siblingDescriptions: 'ignore'` (OAS 3.0, where\n * properties beside a `$ref` are ignored) the component's own is kept. A ref\n * nothing under `components/responses` answers (a pointer into another\n * section, or one a bundler wrote to the first place it inlined a repeated\n * external ref, `#/paths/~1pets/get/responses/200`) is warned about and\n * returned as written, so the response reads as it always did: no body, no\n * headers, its sibling `description` kept. A document that parsed before any\n * response ref was resolved still parses. Only a circular chain throws,\n * since no reader could resolve it. Under `onFailure: 'silent'` neither\n * failure is reported and the ref is returned as written; that is for a\n * reader that only pre-computes names, leaving the report to the operation\n * that declares the ref.\n */\nexport function resolveResponseRef<T extends object>(\n  raw: T | ReferenceObject,\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  context: string,\n  siblingDescriptions: SiblingDocs = 'override',\n  onFailure: 'report' | 'silent' = 'report',\n): T {\n  const followed = followReference<T>(raw, 'responses', componentResponses, siblingDescriptions);\n  if (onFailure === 'report') {\n    if (followed.outcome === 'circular') {\n      throw new Error(`Circular response $ref chain starting at \"${followed.ref}\" in ${context}.`);\n    }\n    // `silent` is for a reader that only pre-computes names from the\n    // component map (`resolvePathModelBaseNames`): the operation that\n    // declares the ref reports the problem once when it reads it, so this\n    // reader neither warns nor throws and returns the ref as written.\n    if (followed.outcome === 'unresolved') {\n      console.warn(\n        `[oagen] Warning: Unresolved response $ref \"${followed.ref}\" in ${context}: no matching entry under components/responses — reading the response as written, without a body or headers`,\n      );\n    }\n  }\n  return followed.value;\n}\n","import type { SecurityRequirementSet } from '../ir/types.js';\n\n/**\n * An OpenAPI security requirement list as written in the document: each\n * object is one alternative whose keys are scheme names and whose values are\n * the scopes that scheme needs.\n */\nexport type RawSecurityRequirements = Array<Record<string, string[] | undefined> | null | undefined>;\n\n/**\n * Convert a document- or operation-level `security` list into the IR shape,\n * preserving what the list says rather than flattening it:\n *\n * - absent (or not a list) → `undefined`: nothing declared here.\n * - `[]` → `[]`: no authentication required.\n * - `[{ a: [] }, { b: [] }]` → `[[a], [b]]`: either scheme suffices.\n * - `[{ a: [], b: [] }]` → `[[a, b]]`: both schemes are required together.\n * - `[{ a: [] }, {}]` → `[[a], []]`: the empty set is an anonymous alternative,\n *   which is how a document marks authentication optional.\n *\n * An entry that is not an object (`null`, say) is not a requirement object.\n * Reading it as `{}` would declare an anonymous alternative and make the\n * operation look open, so it is dropped with an `[oagen] Warning:` naming\n * `context` (the operation, or the document). A non-empty list left with no\n * valid entry is treated as undeclared (`undefined`) rather than as `[]`:\n * the document never said \"no authentication\", so the operation keeps\n * inheriting the default.\n *\n * The previous flattening collapsed the alternatives onto one list and turned\n * `[]` into `undefined`, so \"no auth\" read the same as \"use the default\" and\n * \"either of\" the same as \"all of\" (#182).\n */\nexport function extractSecurityRequirements(\n  security: RawSecurityRequirements | undefined,\n  context: string,\n): SecurityRequirementSet[] | undefined {\n  if (!Array.isArray(security)) return undefined;\n\n  const sets: SecurityRequirementSet[] = [];\n  for (const entry of security) {\n    if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {\n      console.warn(\n        `[oagen] Warning: Ignoring security requirement ${JSON.stringify(entry)} on ${context} — not a requirement object`,\n      );\n      continue;\n    }\n    sets.push(\n      Object.entries(entry).map(([schemeName, scopes]) => ({\n        schemeName,\n        scopes: Array.isArray(scopes) ? scopes : [],\n      })),\n    );\n  }\n  if (security.length > 0 && sets.length === 0) {\n    console.warn(`[oagen] Warning: No valid security requirement on ${context}; treating security as undeclared`);\n    return undefined;\n  }\n  return sets;\n}\n","import type { ServerEntry, ServerVariable } from '../ir/types.js';\nimport { resolveServerUrl } from '../ir/server-url.js';\n\n/** A `servers` entry as written in the OpenAPI document; narrowed field by field. */\nexport interface RawServerObject {\n  url?: unknown;\n  description?: unknown;\n  variables?: unknown;\n}\n\n/** What the document's `servers` list contributes to `ApiSpec`. */\nexport interface ExtractedServers {\n  /** One entry per server that has a URL, in document order; `undefined` when there is none. */\n  servers: ServerEntry[] | undefined;\n  /** The first server's URL with its variables' defaults filled in, or `''` without a server. */\n  baseUrl: string;\n}\n\n/**\n * Convert the document's `servers` list into `ApiSpec.servers` and\n * `ApiSpec.baseUrl`.\n *\n * `ServerEntry.url` stays as written — placeholders included — so an emitter\n * can offer the variables; `baseUrl` is `servers[0]` resolved with\n * `resolveServerUrl`, which fills each `{name}` with the variable's `default`\n * (OpenAPI requires one). The list itself is normalised by\n * `extractServerList`, the same way a Path Item's or an Operation's is.\n *\n * A document that writes OpenAPI's default server out (`servers: [{ url:\n * '/' }]`) is carried as written — `servers: [{ url: '/' }]`, `baseUrl: '/'`\n * — while one that declares none has `servers` absent and `baseUrl: ''`. The\n * two mean the same thing, and everywhere server lists are compared they are\n * read as one: `isDefaultServerList` for `Operation.servers`,\n * `serversOrDefault` and `baseUrlBeyondDefault` in the differ, all in\n * `ir/server-url.ts` (#291).\n */\nexport function extractServers(rawServers: unknown): ExtractedServers {\n  const servers = extractServerList(rawServers, 'the document');\n  const baseUrl = servers ? resolveServerUrl(servers[0]).url : '';\n  return { servers, baseUrl };\n}\n\n/**\n * Normalise a `servers` list — the document's, a Path Item's or an\n * Operation's — into `ServerEntry[]`, or `undefined` when it declares nothing\n * usable. All three levels go through here so they come out identical: the\n * same handling of non-object entries, blank URLs, `variables` and\n * prototype-named keys, and the same warnings, each naming `context` (\"the\n * document\", \"path item /pets\", \"operation listPets\").\n *\n * A non-array, an empty list, and a list whose entries are all unusable (not\n * an object, no `url`, or an empty `url`) all yield `undefined`. OpenAPI gives\n * `servers: []` no meaning as an override — only the document-level default\n * of `/` is defined for an empty list — so at path and operation level\n * `undefined` means \"inherit\".\n *\n * Server variables are the same shape in OpenAPI 3.0 and 3.1. Every server is\n * checked, not only the first, because an emitter may resolve any of them,\n * and each problem is reported once with an `[oagen] Warning:`:\n *\n * - A variable without a usable `default` has no IR representation\n *   (`ServerVariable.default` is required) and is omitted; its placeholder\n *   stays in the URL.\n * - A placeholder that names no declared variable stays in the URL.\n * - A `default` outside the variable's `enum` is kept as written.\n *\n * A declared variable the URL never mentions is kept without comment; it is\n * harmless and an emitter may still expose it. `default` and `enum` entries\n * are strings; a number or boolean (YAML reads `default: 8443` as a number)\n * is carried as its text, anything else is ignored. An empty `enum`, which\n * the specification forbids, is treated as undeclared.\n */\nexport function extractServerList(rawServers: unknown, context: string): ServerEntry[] | undefined {\n  if (!Array.isArray(rawServers)) return undefined;\n  const servers: ServerEntry[] = [];\n  for (const raw of rawServers) {\n    const entry = buildServerEntry(raw, context);\n    if (entry) servers.push(entry);\n  }\n  return servers.length > 0 ? servers : undefined;\n}\n\nfunction buildServerEntry(raw: unknown, context: string): ServerEntry | undefined {\n  if (!isRecord(raw) || typeof raw.url !== 'string' || raw.url === '') return undefined;\n  const url = raw.url;\n  const entry: ServerEntry = { url, description: typeof raw.description === 'string' ? raw.description : undefined };\n\n  const declared = isRecord(raw.variables) ? raw.variables : {};\n  // Collected in a Map and materialized with Object.fromEntries, which defines\n  // own data properties: `variables[name] = …` on a plain object would set its\n  // prototype instead when the document names a variable `__proto__`. The\n  // result is still an ordinary object, so `Object.keys`, JSON and snapshots\n  // see nothing unusual.\n  const variables = new Map<string, ServerVariable>();\n  for (const [name, value] of Object.entries(declared)) {\n    const variable = buildServerVariable(url, context, name, value);\n    if (variable) variables.set(name, variable);\n  }\n  // Absent, not `undefined`, when the document declares none (or none usable).\n  if (variables.size > 0) entry.variables = Object.fromEntries(variables);\n\n  for (const name of resolveServerUrl(entry).unresolved) {\n    // A declared variable that was omitted above has already been reported.\n    if (Object.hasOwn(declared, name)) continue;\n    console.warn(\n      `[oagen] Warning: Server URL \"${url}\" on ${context} uses {${name}} but declares no such variable; the placeholder stays in the URL`,\n    );\n  }\n  return entry;\n}\n\nfunction buildServerVariable(url: string, context: string, name: string, raw: unknown): ServerVariable | undefined {\n  const declared: Record<string, unknown> = isRecord(raw) ? raw : {};\n  const defaultValue = scalarText(declared.default);\n  if (defaultValue === undefined) {\n    console.warn(\n      `[oagen] Warning: Server variable \"${name}\" of \"${url}\" on ${context} has no default (a string is required) and is omitted; its placeholder stays in the URL`,\n    );\n    return undefined;\n  }\n\n  const variable: ServerVariable = { default: defaultValue };\n  const enumValues = Array.isArray(declared.enum)\n    ? declared.enum.map(scalarText).filter((value): value is string => value !== undefined)\n    : [];\n  if (enumValues.length > 0) {\n    variable.enum = enumValues;\n    if (!enumValues.includes(defaultValue)) {\n      console.warn(\n        `[oagen] Warning: Server variable \"${name}\" of \"${url}\" on ${context} defaults to \"${defaultValue}\", which is not one of its enum values (${enumValues.join(', ')}); kept as written`,\n      );\n    }\n  }\n  if (typeof declared.description === 'string') variable.description = declared.description;\n  return variable;\n}\n\n/** A string as itself; a number or boolean as its text; anything else is not a value. */\nfunction scalarText(value: unknown): string | undefined {\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { Field, Model, TypeRef } from '../ir/types.js';\nimport { assertNever, collectModelRefs, renameModelRefs, renameTypeRefModels } from '../ir/types.js';\nimport {\n  fieldPropertiesAdmit,\n  fieldPropertiesKey,\n  flagAdmits,\n  modelPropertiesAdmit,\n  modelPropertiesKey,\n  type InlineModelBundle,\n} from './inline-models.js';\nimport { enumShapeKey, enumValueShapeKey, enumValuesOf } from './enum-members.js';\nimport { unionRulesKey, unionShapeKey } from './union-shape.js';\n\n/**\n * A list-envelope companion that was lifted to one or more inline models:\n * `field` is the envelope field (shared by identity with\n * `Operation.pagination.envelopeFields`), `models[0]` is the companion's own\n * model and the rest are models nested inside it. Every model is named under\n * the operation (`ListUsersListMetadata`); `bareNames[i]` is the name\n * `models[i]` would carry if it were named from its property alone\n * (`ListMetadata`).\n */\nexport interface EnvelopeCompanion {\n  field: Field;\n  models: Model[];\n  bareNames: string[];\n}\n\n/**\n * Decide the final name of every lifted companion model, across all list\n * operations at once, and return the models to merge into the IR.\n *\n * The same envelope recurs on every list endpoint of an API, so naming each\n * copy after its operation would mint one identical `ListMetadata` per\n * endpoint. But naming by property alone is only safe while the copies agree:\n * among inline models `mergeInlineResponseModels` keeps the largest model of\n * a name, so a `pagination` with three fields would absorb another endpoint's\n * two-field `pagination`, and one named like a `Pagination` component that\n * does not admit it would be moved to an operation-qualified name by the\n * merge rather than by this pass.\n *\n * So a companion takes its bare name only when that cannot change any other\n * type's shape:\n *\n * Copies are compared structurally — field names, requiredness and each\n * field's shape, with nested models resolved and inline enums compared by\n * value — never by name alone. A copy collapses onto a target shape only when\n * the target *admits* every value the copy can hold: the same fields with the\n * same types, where the target may be looser (a field the copy requires may be\n * optional on the target, a non-null copy field may be nullable there) but\n * never stricter. Widening a response type loses no data a reader can see;\n * narrowing it would promise fields the wire may omit.\n *\n * - When a component model of that name exists — compared after the parser's\n *   own renaming, so `PaginationDto` → `Pagination` is caught — the copies it\n *   admits collapse onto it (the component stays as written); the others keep\n *   their operation-qualified name.\n * - Otherwise the most common exact shape (first declared, on a tie) becomes\n *   the target: it and every copy it admits take the bare name; any other\n *   copy keeps its operation-qualified name.\n * - `deprecated` is part of a copy's shape among copies, so deprecation never\n *   reaches a live operation and never depends on document order: a copy\n *   folds onto another copy's definition only with the same flag, and while\n *   any live copy exists the target is chosen among the live copies, so a\n *   deprecated copy keeps its operation-qualified name\n *   (`ListLegacyUsersListMetadata`). Only when every copy is deprecated does\n *   a deprecated shape take the bare name. Beside a component, the\n *   companion's own flag is read as every declared model reads it\n *   (`flagAdmits`): a live component admits a deprecated companion — the\n *   envelope field keeps the flag the schema wrote (`Field.deprecated`), so\n *   nothing is lost — with the warning the merge passes give such a copy,\n *   and a deprecated component only a deprecated one. A model nested in the\n *   companion still folds only onto a component of the same flag; the\n *   model's own properties beside the flag — its limits (`minProperties`,\n *   `dependentRequired`, …), type parameters, whatever else the IR adds —\n *   are read as every component fold reads them (`modelPropertiesAdmit`):\n *   identical, so a companion declaring `minProperties: 1` never shares a\n *   component declaring `2`, nor the reverse; and every field is read in\n *   everything but its type as `fieldAdmits` reads it\n *   (`fieldPropertiesAdmit`): its own flag must agree in either direction,\n *   the target may be looser on requiredness only, and limits, default,\n *   access flags and every other property must be identical, since the\n *   target's definition is what every site reads after the fold — a\n *   companion whose `next` is deprecated, or allows 64 characters, never\n *   shares a component whose `next` is live, or allows 8, nor the other way\n *   round, flag or no flag on the root. Among copies the same properties are\n *   part of the shape (`modelPropertiesKey`, `fieldPropertiesKey`), so a\n *   copy that deprecates or limits itself or a field as the others do not\n *   keeps its own name.\n *\n * The comparison covers the companion's whole field type, so a `oneOf`\n * companion is judged on every variant, not just the first, and a copy folds\n * among copies only when its lifted models line up name for name with the\n * target's (same variants, same order); onto a component, only a companion\n * whose field references exactly its own lifted model can fold.\n *\n * Only the target's definition survives a collapse. The admitted copies'\n * models are dropped rather than handed to the merge pass, which keeps the\n * first model of a name and would let a stricter copy declared earlier\n * narrow the shared type for everyone; their field references are repointed\n * at the target's models instead.\n *\n * Enums declared inline in a companion stay operation-qualified, exactly like\n * enums declared inline in a parameter.\n *\n * `foldedOnto`, when given, receives every copy that folded onto another\n * companion's definition, keyed to that companion (a copy folded onto a\n * component is not recorded: nothing of it is emitted), so the caller can\n * tell which envelope fields a surviving companion's models serve\n * (`companionBundles`).\n */\nexport function resolveEnvelopeCompanionNames(\n  companions: EnvelopeCompanion[],\n  componentModels?: Model[],\n  foldedOnto?: Map<EnvelopeCompanion, EnvelopeCompanion>,\n): Model[] {\n  const byBareName = new Map<string, EnvelopeCompanion[]>();\n  /** Copies folded onto another definition; their own models are not emitted. */\n  const folded = new Set<EnvelopeCompanion>();\n  for (const companion of companions) {\n    if (companion.models.length === 0) continue;\n    const bare = companion.bareNames[0];\n    const group = byBareName.get(bare) ?? [];\n    group.push(companion);\n    byBareName.set(bare, group);\n  }\n\n  const componentMap = new Map((componentModels ?? []).map((m) => [m.name, m]));\n  const localMap = (c: EnvelopeCompanion): Map<string, Model> => new Map(c.models.map((m) => [m.name, m]));\n  // A folded copy keeps its own field wrapper and only its references move, so\n  // whether the envelope field itself is nullable has no bearing on folding.\n  const unwrap = (t: TypeRef): TypeRef => (t.kind === 'nullable' ? t.inner : t);\n\n  for (const [bare, group] of byBareName) {\n    // What every copy is measured against: a field type, the map its model\n    // references resolve through (a component through the other components, a\n    // copy through its own models), and the names a folded copy's references\n    // are repointed to.\n    let folds: (c: EnvelopeCompanion) => boolean;\n    let finalNames: string[];\n    let owner: EnvelopeCompanion | undefined;\n\n    const component = componentMap.get(bare);\n    if (component) {\n      const targetType: TypeRef = { kind: 'model', name: component.name };\n      finalNames = [component.name];\n      folds = (c) => {\n        // Only a field that references exactly its own lifted model can be\n        // repointed at the component; a union of variants has nowhere to go.\n        const own = c.models[0]!;\n        const refs = collectModelRefs(c.field.type);\n        if (refs.length !== 1 || refs[0] !== own.name) return false;\n        // The companion's own flag is read by `flagAdmits`, apart from its\n        // shape: a deprecated companion is compared with a live component\n        // as if live, since its envelope field keeps the flag. Its nested\n        // models are compared with theirs (`admits`), flag included.\n        if (!flagAdmits(component, own)) return false;\n        const local = localMap(c);\n        if (own.deprecated && !component.deprecated) local.set(own.name, { ...own, deprecated: undefined });\n        return typeAdmits(targetType, componentMap, unwrap(c.field.type), local, new Set());\n      };\n    } else {\n      const counts = new Map<string, { n: number; first: EnvelopeCompanion }>();\n      // The bare name is owned by a live copy while one exists: a deprecated\n      // copy keeps its operation-qualified name rather than deprecating the\n      // name every live operation shares.\n      const live = group.filter((c) => !c.models[0].deprecated);\n      const candidates = live.length > 0 ? live : group;\n      for (const c of candidates) {\n        const key = `${fingerprintType(unwrap(c.field.type), localMap(c), new Set())}|${c.bareNames.join(',')}`;\n        const seen = counts.get(key);\n        if (seen) seen.n += 1;\n        else counts.set(key, { n: 1, first: c });\n      }\n      let best = { n: 0, first: candidates[0] };\n      for (const entry of counts.values()) if (entry.n > best.n) best = entry;\n      owner = best.first;\n      finalNames = owner.bareNames;\n      const ownerType = unwrap(owner.field.type);\n      const ownerMap = localMap(owner);\n      const ownerNames = owner.bareNames;\n      folds = (c) =>\n        c.bareNames.length === ownerNames.length &&\n        c.bareNames.every((name, i) => name === ownerNames[i]) &&\n        typeAdmits(ownerType, ownerMap, unwrap(c.field.type), localMap(c), new Set());\n    }\n\n    // Decide every copy before renaming any: renaming the target repoints its\n    // nested references to the bare names, which its map no longer resolves.\n    const collapsing = group.filter(folds);\n    for (const companion of collapsing) {\n      // A deprecated copy a live component admits is announced once per\n      // companion, as the merge passes announce one (`settleSharedNames`).\n      if (component && !component.deprecated && companion.models[0]!.deprecated) {\n        console.warn(\n          `[oagen] Warning: Inline model \"${component.name}\" is declared both deprecated and live with the same shape — keeping the live definition under the shared name`,\n        );\n      }\n      renameCompanion(companion, finalNames);\n      if (companion !== owner) {\n        folded.add(companion);\n        if (owner) foldedOnto?.set(companion, owner);\n      }\n    }\n  }\n\n  return companions.filter((c) => !folded.has(c)).flatMap((c) => c.models);\n}\n\n/**\n * One site (`InlineModelBundle`) per companion that kept its models after\n * `resolveEnvelopeCompanionNames`: the envelope field that lifted it, plus\n * the envelope field of every copy that folded onto it (`foldedOnto`) — those\n * fields were repointed at its models and reference nothing else — so a merge\n * pass that later renames one of its models (a deprecated companion named\n * like a live component field's model, say) repoints every operation that\n * shares it, and nothing else. `survivingModels` is what the resolver\n * returned; a companion is a survivor when its own model is among them.\n * `qualifiers` gives each companion the PascalCase name of the operation that\n * lifted it, to prefix a renamed model as a header model is prefixed.\n */\nexport function companionBundles(\n  companions: EnvelopeCompanion[],\n  survivingModels: Model[],\n  foldedOnto: ReadonlyMap<EnvelopeCompanion, EnvelopeCompanion>,\n  qualifiers: ReadonlyMap<EnvelopeCompanion, string>,\n): InlineModelBundle[] {\n  const surviving = new Set(survivingModels);\n  const bundles: InlineModelBundle[] = [];\n  for (const companion of companions) {\n    const own = companion.models[0];\n    if (!own || !surviving.has(own)) continue;\n    const sharers = companions.filter((c) => foldedOnto.get(c) === companion);\n    bundles.push({\n      qualifier: qualifiers.get(companion) ?? '',\n      roots: [companion.field.type, ...sharers.map((c) => c.field.type)],\n      models: companion.models,\n    });\n  }\n  return bundles;\n}\n\n/**\n * Rename a companion's models to `names` (index-aligned with `models`) and\n * repoint every reference, in its field and inside its models — a union\n * companion's discriminator mapping with its variants (`renameTypeRefModels`).\n */\nfunction renameCompanion(companion: EnvelopeCompanion, names: string[]): void {\n  const renames = new Map<string, string>();\n  companion.models.forEach((model, i) => {\n    const name = names[i];\n    if (name !== undefined && model.name !== name) renames.set(model.name, name);\n  });\n  if (renames.size === 0) return;\n\n  renameTypeRefModels(companion.field.type, renames);\n  for (const model of companion.models) {\n    model.name = renames.get(model.name) ?? model.name;\n    renameModelRefs(model, renames);\n  }\n}\n\n/**\n * Whether `target` admits every value `copy` can hold: the same field names,\n * each field's type admitted (see `typeAdmits`), and no field the target\n * requires that the copy leaves optional. Nested models resolve through their\n * respective maps and are compared the same way; a model neither map resolves\n * is compared by name.\n */\nfunction admits(\n  target: Model,\n  targetMap: Map<string, Model>,\n  copy: Model,\n  copyMap: Map<string, Model>,\n  visiting: Set<string>,\n): boolean {\n  const key = `${target.name}|${copy.name}`;\n  if (visiting.has(key)) return true;\n  visiting.add(key);\n  try {\n    // Deprecation is part of the shape among copies: a live target must not\n    // absorb a deprecated copy (its flag would vanish), and a deprecated\n    // target must not absorb a live one (a live operation would then\n    // reference it). Beside a component the caller has already read the\n    // root flag by `flagAdmits` and stripped it from the copy.\n    if (!!target.deprecated !== !!copy.deprecated) return false;\n    // Every other property of the model itself — its limits\n    // (`minProperties`, `dependentRequired`, …), type parameters, whatever\n    // else the IR adds — is read as every component fold reads it\n    // (`modelPropertiesAdmit`): identical, since the target's definition is\n    // what every site reads after a fold.\n    if (!modelPropertiesAdmit(target, copy)) return false;\n    if (target.fields.length !== copy.fields.length) return false;\n    const targetFields = new Map(target.fields.map((f) => [f.name, f]));\n    for (const field of copy.fields) {\n      const expected = targetFields.get(field.name);\n      if (!expected) return false;\n      // Everything but the type is read as `fieldAdmits` reads it\n      // (`fieldPropertiesAdmit`): the flag agrees in either direction, the\n      // target is no stricter on requiredness, and limits, default, access\n      // flags and every other property are identical — the target's fields\n      // are what every site reads after a fold. The type is compared by\n      // structure below, since a companion's nested models and inline enums\n      // are named per operation.\n      if (!fieldPropertiesAdmit(expected, field)) return false;\n      if (!typeAdmits(expected.type, targetMap, field.type, copyMap, visiting)) return false;\n    }\n    // A named union is its variants — the same ones, in the same order —\n    // dispatched by the same rules (composition keyword, discriminator).\n    if (unionRulesKey(target) !== unionRulesKey(copy)) return false;\n    const targetVariants = target.variants ?? [];\n    const copyVariants = copy.variants ?? [];\n    if (targetVariants.length !== copyVariants.length) return false;\n    for (let i = 0; i < copyVariants.length; i++) {\n      if (!typeAdmits(targetVariants[i]!, targetMap, copyVariants[i]!, copyMap, visiting)) return false;\n    }\n    return true;\n  } finally {\n    visiting.delete(key);\n  }\n}\n\n/**\n * Whether `target` admits every value of `copy`'s type. A nullable target\n * admits a nullable or a non-null copy; a non-null target admits only a\n * non-null copy. An enum with known values admits a copy whose members are a\n * subset of its own — a member being a value with its deprecation\n * (`enumValueShapeKey`), so a copy deprecating a value the target does not\n * is not admitted. Everything else must match exactly, by fingerprint.\n */\nfunction typeAdmits(\n  target: TypeRef,\n  targetMap: Map<string, Model>,\n  copy: TypeRef,\n  copyMap: Map<string, Model>,\n  visiting: Set<string>,\n): boolean {\n  if (target.kind === 'nullable') {\n    return typeAdmits(target.inner, targetMap, copy.kind === 'nullable' ? copy.inner : copy, copyMap, visiting);\n  }\n  if (copy.kind === 'nullable') return false;\n  if (target.kind !== copy.kind) return false;\n  switch (target.kind) {\n    case 'model': {\n      const t = targetMap.get(target.name);\n      const c = copyMap.get((copy as typeof target).name);\n      if (t && c) return admits(t, targetMap, c, copyMap, visiting);\n      return target.name === (copy as typeof target).name;\n    }\n    case 'array':\n      return typeAdmits(target.items, targetMap, (copy as typeof target).items, copyMap, visiting);\n    case 'enum': {\n      const c = copy as typeof target;\n      if (target.values && c.values) {\n        const allowed = new Set(enumValuesOf(target).map(enumValueShapeKey));\n        return enumValuesOf(c).every((v) => allowed.has(enumValueShapeKey(v)));\n      }\n      return target.name === c.name;\n    }\n    default:\n      return fingerprintType(target, targetMap, new Set()) === fingerprintType(copy, copyMap, new Set());\n  }\n}\n\n/**\n * Structural fingerprint of a companion model: the model's own properties as\n * `modelPropertiesAdmit` reads them (`modelPropertiesKey`: whether it is\n * deprecated, its limits, its type parameters), its field names, each\n * field's properties as `fieldPropertiesAdmit` reads them\n * (`fieldPropertiesKey`: requiredness, its own deprecation, limits, default,\n * access flags) and each field's shape, with models nested\n * inside the companion compared by shape rather than by (operation-qualified)\n * name, and inline enums compared by their members — each value with its\n * deprecation (`enumValueShapeKey`), so a copy deprecating a value the others\n * do not keeps its own name, as a deprecated copy of a model does. Models\n * outside the companion are compared by name.\n */\nfunction fingerprintModel(model: Model, local: Map<string, Model>, visiting: Set<string>): string {\n  if (visiting.has(model.name)) return `rec:${model.name}`;\n  visiting.add(model.name);\n  const fields = [...model.fields]\n    .sort((a, b) => a.name.localeCompare(b.name))\n    .map((f) => `${f.name}${fieldPropertiesKey(f)}:${fingerprintType(f.type, local, visiting)}`);\n  // A named union's variants, in document order, and its dispatch rules are\n  // part of its shape.\n  const union = unionShapeKey(model, (v) => fingerprintType(v, local, visiting));\n  visiting.delete(model.name);\n  return `${modelPropertiesKey(model)}{${fields.join(',')}}${union}`;\n}\n\nfunction fingerprintType(ref: TypeRef, local: Map<string, Model>, visiting: Set<string>): string {\n  switch (ref.kind) {\n    case 'primitive':\n      return `p:${ref.type}${ref.format ? `:${ref.format}` : ''}`;\n    case 'literal':\n      return `l:${typeof ref.value}:${String(ref.value)}`;\n    case 'nullable':\n      return `n<${fingerprintType(ref.inner, local, visiting)}>`;\n    case 'array':\n      return `a<${fingerprintType(ref.items, local, visiting)}>`;\n    case 'map':\n      return `m<${ref.keyType ? `${fingerprintType(ref.keyType, local, visiting)},` : ''}${fingerprintType(ref.valueType, local, visiting)}>`;\n    case 'union':\n      return `u:${ref.compositionKind ?? ''}<${ref.variants\n        .map((v) => fingerprintType(v, local, visiting))\n        .sort()\n        .join(',')}>`;\n    case 'enum':\n      return ref.values ? `e<${enumShapeKey(enumValuesOf(ref))}>` : `e:${ref.name}`;\n    case 'model': {\n      const nested = local.get(ref.name);\n      return nested ? fingerprintModel(nested, local, visiting) : `ref:${ref.name}`;\n    }\n    default:\n      return assertNever(ref);\n  }\n}\n","/**\n * Report an Operation Object's `callbacks` (OpenAPI 3.x), which the parser\n * does not read.\n *\n * A callback is a request the API makes back to a URL the caller supplied in\n * the operation's request: a path item keyed by a runtime expression such as\n * `{$request.body#/callbackUrl}`. The IR has no node for a request tied to\n * the operation that provoked it, so a callback's request body never becomes\n * a model and an SDK cannot type what it receives. Rather than lose that\n * quietly, every site that reads an operation declaring at least one\n * callback says so once, with the callback keys, the way a document carrying\n * `x-webhooks` is told (see `warnOnLegacyWebhooks` in `parse.ts`). The path\n * item under a callback has the shape of a `webhooks` entry, which is read,\n * so the message says where to declare it to have its payload typed.\n *\n * Shared by the two sites that read an Operation Object — a `paths` operation\n * (`buildOperation`, once per operation) and a `webhooks` (key, method) entry\n * (`collectWebhookEntries`, once per entry: two keys that `$ref` one\n * `components/pathItems` entry are two sites and are each reported) — so the\n * two cannot drift. `label` names the site as the other warnings do: the\n * `operationId`, else `METHOD /path`; `webhooks.<key>.<method>` for a\n * webhook. An empty map, or a value that is not a map, declares no callback\n * and is silent. A `$ref` into `components/callbacks` is reported at the\n * operation that writes it, under its key; an entry there that no operation\n * references is not reported, since nothing reaches it.\n */\nexport function warnOnIgnoredCallbacks(callbacks: unknown, label: string): void {\n  if (typeof callbacks !== 'object' || callbacks === null || Array.isArray(callbacks)) return;\n  const names = Object.keys(callbacks);\n  if (names.length === 0) return;\n  console.warn(\n    `[oagen] Warning: \\`callbacks\\` on ${label} are not read (${names.map((name) => `\"${name}\"`).join(', ')}); ` +\n      \"the operation is parsed without them. Declare each callback's request under the top-level \" +\n      '`webhooks` map (OpenAPI 3.1) to have its payload typed.',\n  );\n}\n","import type {\n  Service,\n  Operation,\n  HttpMethod,\n  Parameter,\n  ParameterGroup,\n  TypeRef,\n  ErrorResponse,\n  SuccessResponse,\n  ResponseHeader,\n  ResponseContent,\n  RequestBodyContent,\n  Enum,\n  DefaultResponse,\n  RangeResponse,\n  Model,\n  Field,\n  PaginationMeta,\n  PaginationEndOfIteration,\n  ExternalDocs,\n  ServerEntry,\n  StatusRange,\n} from '../ir/types.js';\nimport { pathSegments, readPath, type OperationHint } from '../ir/operation-hints.js';\nimport { isDefaultServerList, serverListsEqual } from '../ir/server-url.js';\nimport { foldHeaderName, foldParameterName, parameterKey } from '../ir/parameter-key.js';\nimport { createHash } from 'node:crypto';\nimport {\n  toPascalCase,\n  toCamelCase,\n  splitWords,\n  cleanSchemaName,\n  stripListItemMarkers,\n  singularizePathSegment,\n} from '../utils/naming.js';\nimport { isJsonMediaType, isPlainJsonMediaType, mediaTypeEssence, mediaTypeNameFragment } from '../utils/media-type.js';\nimport type { SchemaObject } from './schemas.js';\nimport {\n  schemaToTypeRef,\n  buildFieldFromSchema,\n  nameInlineVariant,\n  resolveSchemaName,\n  nonEmptyExamples,\n  resolveExamples,\n  resolveComponentSchemaRef,\n  extractConstraints,\n  constraintsEntry,\n  deprecatedEntry,\n  collapsedNullableBranch,\n  foldSiblingProperties,\n  inlineEnumSchemaName,\n  isComponentModelRef,\n  isInlineObjectSchema,\n  nonObjectVariantContexts,\n  unwrapNullableField,\n  warnOnUncarriedProperties,\n} from './schemas.js';\nimport {\n  collectResponseHeaders,\n  collectModelRefs,\n  collectModelTypeRefs,\n  collectEnumRefs,\n  collectOperationTypeRefs,\n  renameModelRefs,\n  renameTypeRefModels,\n  walkTypeRef,\n  type ModelRef,\n} from '../ir/types.js';\nimport {\n  agreedExtensions,\n  collectProperties,\n  extractInlineModelsFromProperties,\n  isInheritedModelRef,\n  withAgreedExtensions,\n  type InlineModelBundle,\n} from './inline-models.js';\nimport {\n  SCHEMA_CONSUMED_EXTENSIONS,\n  extensionsOf,\n  operationExtensionsEntry,\n  schemaExtensionsEntry,\n} from './extensions.js';\nimport {\n  detectPagination,\n  derivePageStart,\n  describeUndetectedPaging,\n  paginatedItemType,\n  resolvePaginationOverride,\n  resolveOverrideParams,\n  applyPaginationOverride,\n  resolveDataPathItemType,\n} from './pagination.js';\nimport {\n  BODY_READINGS,\n  bodyEndOfIterationProblem,\n  bodyTypesAsUnknown,\n  classifyAndExtractResponse,\n  composedWithoutFields,\n  classifyResponseKey,\n  isErrorStatusRange,\n  resolveDataPathFromSchema,\n  STATUS_RANGE_LABELS,\n  warnUnrecognizedResponseKey,\n} from './responses.js';\nimport type { ResponseKey } from './responses.js';\nimport type { ItemSettlement, ResponseExtractionResult } from './responses.js';\nimport { resolveResponseRef, type ReferenceObject } from './response-refs.js';\nimport {\n  materializeInlineSchema,\n  modelFingerprint,\n  ownerShares,\n  registerInlineModels,\n  reserveEnumNames,\n  type InlineModelRegistry,\n  type InlineModelOwner,\n  type SiblingSites,\n  createSiblingSites,\n} from './materialize-inline.js';\nimport { extractSecurityRequirements, type RawSecurityRequirements } from './security.js';\nimport { extractServerList } from './servers.js';\nimport { resolveEnvelopeCompanionNames, companionBundles, type EnvelopeCompanion } from './envelope-companion-names.js';\nimport { externalDocsEntry, readExternalDocs, type RawExternalDocs } from './external-docs.js';\nimport { warnOnIgnoredCallbacks } from './callbacks.js';\nimport { resolvePathItemRef } from './path-item-refs.js';\nimport { followReference, siblingDocsMode, type SiblingDocs } from './reference-objects.js';\n\nexport interface PathItem {\n  /**\n   * A reference to another Path Item, which OpenAPI 3.1 lets a `paths` entry\n   * be written as (`$ref: '#/components/pathItems/Pets'`). Resolved by\n   * `resolvePathItems` before anything else is read from the entry, so no\n   * item the passes of `extractOperations` read carries one.\n   */\n  $ref?: string;\n  /**\n   * The Path Item's own `summary`, which OpenAPI applies to every operation\n   * on it; read for an operation that declares none (`resolveOperationDocs`).\n   */\n  summary?: string;\n  /** The Path Item's own `description`, applied to its operations the same way. */\n  description?: string;\n  get?: OperationObject;\n  post?: OperationObject;\n  put?: OperationObject;\n  patch?: OperationObject;\n  delete?: OperationObject;\n  head?: OperationObject;\n  options?: OperationObject;\n  trace?: OperationObject;\n  parameters?: RawParameterObject[];\n  /** The Path Item's own `servers`, narrowed entry by entry by `extractServerList`. */\n  servers?: unknown;\n}\n\ninterface ParameterGroupExtension {\n  optional: boolean;\n  variants: Record<string, string[]>;\n  /** Per-variant names that may be omitted when the variant is used. */\n  optionalFields?: Record<string, string[]>;\n}\n\nexport interface OperationObject {\n  operationId?: string;\n  summary?: string;\n  description?: string;\n  tags?: string[];\n  externalDocs?: RawExternalDocs;\n  parameters?: RawParameterObject[];\n  requestBody?: RawRequestBodyObject;\n  responses?: Record<string, ResponseObject>;\n  deprecated?: boolean;\n  'x-oagen-async'?: boolean;\n  /** Explicit pagination override; validated by `applyPaginationOverrides`. */\n  'x-pagination'?: unknown;\n  security?: RawSecurityRequirements;\n  /** The operation's own `servers`, narrowed entry by entry by `extractServerList`. */\n  servers?: unknown;\n  'x-mutually-exclusive-parameter-groups'?: Record<string, ParameterGroupExtension>;\n  'x-mutually-exclusive-body-groups'?: Record<string, ParameterGroupExtension>;\n  /** Not read; `warnOnIgnoredCallbacks` reports an operation that declares any. */\n  callbacks?: unknown;\n}\n\n/**\n * An OAS Example Object, as the entries of a parameter's `examples` map and\n * of `components.examples`. Only `value` is read: a `$ref` entry is first\n * resolved against `components.examples` (see `resolveExampleRef`), and an\n * entry that carries `externalValue` instead has no inline value to surface.\n */\ninterface ExampleObject {\n  summary?: string;\n  description?: string;\n  value?: unknown;\n  externalValue?: string;\n  $ref?: string;\n}\n\n/**\n * The Media Type Object a Parameter Object's or Header Object's `content`\n * map holds under a media type: the schema that types the value and the\n * examples beside it. `encoding` is not read.\n */\nexport interface ParameterMediaTypeObject {\n  schema?: SchemaObject;\n  example?: unknown;\n  /** Media-type-level examples: a map of Example Objects, as the parameter's own `examples` is. */\n  examples?: Record<string, ExampleObject>;\n}\n\n/**\n * What a Parameter Object or Header Object types its value with: a\n * `schema`, or a `content` map in its place — per OAS one or the other,\n * never both, and the map holds one entry. `parameterTyping` resolves the\n * schema either way.\n */\nexport interface SchemaOrContent {\n  schema?: SchemaObject;\n  content?: Record<string, ParameterMediaTypeObject>;\n}\n\nexport interface ParameterObject extends SchemaOrContent {\n  name: string;\n  in: 'path' | 'query' | 'header' | 'cookie';\n  required?: boolean;\n  description?: string;\n  deprecated?: boolean;\n  example?: unknown;\n  /** Parameter-level examples: a map of Example Objects, not a JSON Schema list. */\n  examples?: Record<string, ExampleObject>;\n  style?: string;\n  explode?: boolean;\n}\n\n/**\n * A parameter entry as it appears in an operation's (or path item's) raw\n * `parameters` array: either an inline Parameter Object, or a Reference\n * Object (`{ $ref: '#/components/parameters/X' }`). The bundler\n * (`refs.ts`) runs with `dereference: false`, so refs to\n * `components/parameters` are never inlined — they arrive here exactly as\n * written in the spec and must be resolved before use.\n */\nexport type RawParameterObject = ParameterObject | { $ref: string };\n\n/**\n * Resolve a raw parameter entry to a concrete Parameter Object, following\n * `$ref`s into `components/parameters` when present — chains included, with\n * a cycle guard — through `followReference`, the walk every Reference Object\n * takes. A `description` written beside a ref is the parameter's own under\n * `siblingDocs: 'override'` (OAS 3.1), the outermost with content winning\n * along a chain, and is ignored under `'ignore'` (OAS 3.0).\n *\n * Throws when a `$ref` can't be resolved so a malformed spec fails loudly at\n * parse time instead of silently losing the parameter (see `extractParams`,\n * which used to drop any entry with no `in` field — every `$ref` object has\n * none).\n */\nexport function resolveParameterRef(\n  raw: RawParameterObject,\n  componentParameters: Record<string, Record<string, unknown>> | undefined,\n  operationContext: string,\n  siblingDocs: SiblingDocs = 'override',\n): ParameterObject {\n  const followed = followReference<ParameterObject>(raw, 'parameters', componentParameters, siblingDocs);\n  if (followed.outcome === 'circular') {\n    throw new Error(`Circular parameter $ref chain starting at \"${followed.ref}\" in ${operationContext}.`);\n  }\n  if (followed.outcome !== 'resolved') {\n    throw new Error(\n      `Unresolved parameter $ref \"${followed.ref}\" in ${operationContext}: no matching entry under components/parameters.`,\n    );\n  }\n  return followed.value;\n}\n\nexport interface RequestBodyObject {\n  description?: string;\n  required?: boolean;\n  content?: Record<string, { schema?: SchemaObject }>;\n}\n\n/**\n * A request body as written in the spec: an inline Request Body Object or a\n * Reference Object into `components/requestBodies`. The bundler never inlines\n * those refs (`dereference: false`), so they must be resolved before use.\n */\nexport type RawRequestBodyObject = RequestBodyObject | { $ref: string };\n\n/**\n * Resolve a raw request body to a concrete Request Body Object, following\n * `$ref` chains into `components/requestBodies` with a cycle guard, through\n * `followReference`, the walk every Reference Object takes. A `description`\n * written beside a ref is the body's own under `siblingDocs: 'override'`\n * (OAS 3.1), the outermost with content winning along a chain, and is\n * ignored under `'ignore'` (OAS 3.0) — so `requestBodyDescriptionOf` reads\n * it ahead of the shared body's. Throws on an unresolvable ref so a\n * malformed spec fails at parse time instead of silently losing the body —\n * and with it the body-ownership rule that keeps duplicated secrets out of\n * the query string.\n */\nexport function resolveRequestBodyRef(\n  raw: RawRequestBodyObject | undefined,\n  componentRequestBodies: Record<string, Record<string, unknown>> | undefined,\n  operationContext: string,\n  siblingDocs: SiblingDocs = 'override',\n): RequestBodyObject | undefined {\n  if (!raw) return undefined;\n  const followed = followReference<RequestBodyObject>(raw, 'requestBodies', componentRequestBodies, siblingDocs);\n  if (followed.outcome === 'circular') {\n    throw new Error(`Circular request body $ref chain starting at \"${followed.ref}\" in ${operationContext}.`);\n  }\n  if (followed.outcome !== 'resolved') {\n    throw new Error(\n      `Unresolved request body $ref \"${followed.ref}\" in ${operationContext}: no matching entry under components/requestBodies.`,\n    );\n  }\n  return followed.value;\n}\n\n/**\n * A Header Object as it appears in a Response Object's `headers` map. Per OAS\n * it carries either `schema` or a single-entry `content` map, never both;\n * the schema that types it is resolved as a parameter's is\n * (`parameterTyping`).\n */\ninterface HeaderObject extends SchemaOrContent {\n  description?: string;\n  required?: boolean;\n  deprecated?: boolean;\n}\n\n/**\n * A header entry as written in the spec: an inline Header Object or a\n * Reference Object into `components/headers`. The bundler never inlines those\n * refs (`dereference: false`), so they must be resolved before use. In OAS 3.1\n * a Reference Object may carry its own `description`, which overrides the\n * referenced component's.\n */\ntype RawHeaderObject = HeaderObject | { $ref: string; description?: string };\n\n/**\n * Resolve a raw response header to a concrete Header Object, following `$ref`\n * chains into `components/headers` with a cycle guard, through\n * `followReference`, the walk every Reference Object takes. A `description`\n * written beside a ref is the header's own under `siblingDocs: 'override'`\n * (OAS 3.1), the outermost with content winning along a chain, and is\n * ignored under `'ignore'` (OAS 3.0).\n *\n * Unlike parameters and request bodies, a header that cannot be resolved is\n * warned about and dropped rather than failing the parse: a response header\n * is informational, so losing one costs an emitter a typed accessor, not a\n * wire contract, and should not block generating the rest of the SDK.\n */\nfunction resolveHeaderRef(\n  raw: RawHeaderObject,\n  componentHeaders: Record<string, Record<string, unknown>> | undefined,\n  headerName: string,\n  operationContext: string,\n  siblingDocs: SiblingDocs = 'override',\n): HeaderObject | undefined {\n  const followed = followReference<HeaderObject>(raw, 'headers', componentHeaders, siblingDocs);\n  if (followed.outcome === 'circular') {\n    console.warn(\n      `[oagen] Warning: Circular header $ref chain starting at \"${followed.ref}\" for response header ` +\n        `\"${headerName}\" in ${operationContext}. Skipping the header.`,\n    );\n    return undefined;\n  }\n  if (followed.outcome !== 'resolved') {\n    console.warn(\n      `[oagen] Warning: Unresolved header $ref \"${followed.ref}\" for response header \"${headerName}\" ` +\n        `in ${operationContext}: no matching entry under components/headers. Skipping the header.`,\n    );\n    return undefined;\n  }\n  return followed.value;\n}\n\nexport interface ResponseObject {\n  description?: string;\n  headers?: Record<string, RawHeaderObject>;\n  content?: Record<string, { schema?: SchemaObject }>;\n}\n\nexport const HTTP_METHODS: HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];\n\n/**\n * The `paths` map with every entry resolved to the Path Item it denotes —\n * the entry itself, or the `components/pathItems` item its `$ref` leads to\n * (OpenAPI 3.1) — in document order, through `resolvePathItemRef`, the\n * resolver a `webhooks` entry goes through too. A key starting with `x-` is\n * a specification extension of the Paths Object, not a path, and is\n * stepped over without a warning whatever its value, as\n * `collectWebhookEntries` steps over one under `webhooks`. Resolved once,\n * before any pass reads the map, so the model-name reservation\n * (`resolvePathModelBaseNames`), the API root (`documentApiRoot`) and the\n * operation loop all see the same items, and a referenced item's\n * operations, `parameters`, `servers`, `summary` and `description` are read\n * exactly as an inline item's (fields written beside the `$ref` are not, and\n * the resolver reports them). An entry the resolver rejects — not an\n * object, a non-string `$ref`, a ref outside `components/pathItems`, a\n * dangling ref, a cycle — is warned about once, naming the path, and left\n * out. Two paths that `$ref` one entry map to one object, read once per\n * path.\n */\nfunction resolvePathItems(\n  paths: Record<string, PathItem>,\n  componentPathItems: Record<string, Record<string, unknown>> | undefined,\n): Record<string, PathItem> {\n  const resolved: Record<string, PathItem> = {};\n  for (const [path, raw] of Object.entries(paths)) {\n    // A specification extension of the Paths Object, never a path item:\n    // stepped over whatever its value, before the resolver can warn about it.\n    if (path.startsWith('x-')) continue;\n    const pathItem = resolvePathItemRef(raw, componentPathItems, { kind: 'path', key: path });\n    if (pathItem) resolved[path] = pathItem as PathItem;\n  }\n  return resolved;\n}\n\nexport interface OperationExtractionResult {\n  services: Service[];\n  inlineModels: Model[];\n  /**\n   * Where the operations' inline models came from — one bundle per response\n   * and per request body that produced any — so a merge pass can rename a\n   * copy that must not share its name and repoint exactly that operation's\n   * references. List-envelope companions are not bundled:\n   * `resolveEnvelopeCompanionNames` settles their names once and for all.\n   */\n  inlineModelBundles: InlineModelBundle[];\n  /**\n   * Every type reference a site shared through `components/responses` wrote\n   * (`componentSite`: the component's fallback or error body, a secondary\n   * body, a header), by identity — the parser's one record of which sites a\n   * component owns, which the IR alone cannot tell (`CardXMode` is a shared\n   * header's enum name wherever the component is returned). The enum\n   * collector reads it so an enum such a site carries steps by number from\n   * the component's stem (`CardXMode2`), never by the status code or\n   * fallback label that mounted the component, nor by the `Body` an\n   * operation's own error body steps by: an error site — `errors[].type`, a\n   * secondary body of an error entry, a `4XX`/`5XX` range's body — that is\n   * not here is the operation's own, written as `<Op>Error<code>…`, and\n   * steps to `…Body` (`collectInlineEnumsFromOperations`).\n   */\n  componentSites: ReadonlySet<TypeRef>;\n}\n\n/** A top-level `tags[]` entry as it appears in the OpenAPI document. */\nexport interface TagObject {\n  name?: string;\n  description?: string;\n  externalDocs?: RawExternalDocs;\n}\n\nexport function extractOperations(\n  paths: Record<string, PathItem> | undefined,\n  operationIdTransform?: (id: string) => string,\n  componentSchemas?: Record<string, SchemaObject>,\n  componentParameters?: Record<string, Record<string, unknown>>,\n  componentRequestBodies?: Record<string, Record<string, unknown>>,\n  componentModels?: Model[],\n  documentTags?: TagObject[],\n  componentExamples?: Record<string, Record<string, unknown>>,\n  componentHeaders?: Record<string, Record<string, unknown>>,\n  componentResponses?: Record<string, Record<string, unknown>>,\n  componentFieldModels?: Model[],\n  documentServers?: ServerEntry[],\n  openapiVersion?: string,\n  operationHints?: Record<string, OperationHint>,\n  /** The component enums, whose names no deferred or item model may take (see `reserveEnumNames`). */\n  componentEnums?: readonly Enum[],\n  componentPathItems?: Record<string, Record<string, unknown>>,\n): OperationExtractionResult {\n  if (!paths) return { services: [], inlineModels: [], inlineModelBundles: [], componentSites: new Set() };\n\n  // Every pass below reads the resolved map: each entry as itself, or as the\n  // `components/pathItems` item its `$ref` leads to, with an entry that\n  // resolves to nothing left out after one warning (see resolvePathItems).\n  const resolvedPaths = resolvePathItems(paths, componentPathItems);\n\n  // Whether text written beside a `$ref` overrides the referenced component's\n  // (OAS 3.1, and a version not recognised) or is ignored (OAS 3.0), for every\n  // Reference Object the operations resolve (`followReference`): parameters,\n  // request bodies, responses, headers and examples alike.\n  const refSiblingDescriptions = siblingDocsMode(openapiVersion);\n\n  // Operations without an operationId name their inline models from the\n  // path, and two distinct paths — or a path and an operationId, component\n  // schema or component response — can produce the same name, so the prefix\n  // for every such operation is decided up front (see resolvePathModelBaseNames).\n  // The model name each component response's inline body takes, decided once\n  // for every operation that returns it (see resolveComponentResponseModelNames).\n  const componentResponseNaming = resolveComponentResponseModelNames(\n    componentResponses,\n    [...(componentModels ?? []), ...(componentFieldModels ?? [])],\n    componentSchemas,\n  );\n  const componentResponseModelNames = new Map(\n    [...componentResponseNaming].map(([componentName, naming]) => [componentName, naming.name]),\n  );\n  const pathModelBaseNames = resolvePathModelBaseNames(\n    resolvedPaths,\n    componentModels,\n    componentRequestBodies,\n    componentResponseNaming,\n  );\n  // An API root the untagged paths sit under (`/api`, `/v1`) tells the\n  // services apart no better than nothing, so untagged operations skip it\n  // when their service and fallback name are taken from the path (see\n  // documentApiRoot). Tagged operations are named exactly as before.\n  const apiRoot = documentApiRoot(resolvedPaths);\n\n  const serviceMap = new Map<string, Operation[]>();\n  const inlineModels: Model[] = [];\n  const inlineModelBundles: InlineModelBundle[] = [];\n  const envelopeCompanions: EnvelopeCompanion[] = [];\n  /** The PascalCase operation name each companion was lifted under, to qualify it should a merge pass rename it. */\n  const companionQualifiers = new Map<EnvelopeCompanion, string>();\n  // Service name each tagged operation was grouped under, keyed by operation\n  // identity. The path-prefix split below moves operations between services,\n  // so this is how a split-off service is traced back to the tag it came from.\n  const tagServiceByOperation = new Map<Operation, string>();\n  // Operations named from the method and path rather than an operationId.\n  // Only these may be renamed when names collide within a service (see\n  // disambiguateOperationNames); a name taken from an operationId is kept as is.\n  const pathNamed = new Set<Operation>();\n  // Header, secondary-body, fallback-body, error-body and parameter schemas\n  // are typed only after this loop, once every primary model is known\n  // (`resolveDeferredInlineTypes`): their names must not collide with a\n  // differently shaped component, request body or primary response of any\n  // operation, or the later merge would overwrite the first. The registry\n  // records which operation minted each model, and which operation's own\n  // reference carries each enum name (`qualifierOf`), so a clash within one\n  // operation can be told from one across two.\n  const deferred: DeferredInlineType[] = [];\n  const qualifierOf = new Map<Operation, string>();\n  // The spec-wide registry of model shapes (`InlineModelRegistry`), seeded\n  // with every name decided before the operations — the component models\n  // and enums, the components' field models (a nested object, a map's\n  // values; not among `componentModels`, see parseSpec) and the enums their\n  // fields mint — and filled as the operations are read: each operation's\n  // models once it is built, its array items as they are typed\n  // (`typeInlineItems` settles them against it), the envelope companions\n  // once named, and every enum the operations mint. The deferred schemas are\n  // named against all of it last.\n  const registry: ModelShapeRegistry = new Map();\n  const registeredModels = [...(componentModels ?? []), ...(componentFieldModels ?? [])];\n  // Each seeded with the model itself: a declared model shares its name with\n  // every shape it admits (`ownerShares`), an operation's with an identical\n  // one only.\n  for (const model of registeredModels) {\n    if (!registry.has(model.name)) registry.set(model.name, { fingerprint: modelFingerprint(model), model });\n  }\n  // Every enum name decided so far, held as names no model may take\n  // (`reserveEnumNames`): the component enums', and every enum the component\n  // models and the components' field models reference (an inline enum's\n  // `EnumRef`, named before the enum collector may rename it; a `$ref` to a\n  // component enum names one already held). None is an operation's. The\n  // operations' own join once they are read, below.\n  const enumRefsOf = (model: Model): string[] => collectModelTypeRefs(model).flatMap(collectEnumRefs);\n  reserveEnumNames(registry, [...(componentEnums ?? []).map((e) => e.name), ...registeredModels.flatMap(enumRefsOf)]);\n\n  for (const [path, pathItem] of Object.entries(resolvedPaths)) {\n    // Everything read at path-item level — `parameters`, `servers`, and the\n    // `summary`/`description` an operation falls back to — comes from this one\n    // object: the entry itself, or the `components/pathItems` item its `$ref`\n    // leads to, resolved by `resolvePathItems` above (issue #300).\n    const pathLevelParams = pathItem.parameters ?? [];\n    // Read once per Path Item so a problem in its `servers` is reported once,\n    // not once per operation. The operations that inherit it share the array,\n    // the way `responseHeaders` shares its list with `successResponses`.\n    const pathLevelServers = extractServerList(pathItem.servers, `path item ${path}`);\n\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op) continue;\n\n      // The first usable tag — `Operation.tags[0]`, read by the same helper —\n      // so the service and the list the IR carries never disagree, and an\n      // entry that is not a string (`42`) never reaches PascalCasing.\n      const tag = extractTags(op.tags)?.[0];\n      const apiRootLength = tag ? 0 : apiRootLengthOf(path, apiRoot);\n      const serviceName = inferServiceName(path, tag, apiRootLength);\n      const pathModelBaseName = pathModelBaseNames.get(`${method} ${path}`) ?? derivePathModelBaseName(path, method);\n      const servers = operationServers(\n        extractServerList(op.servers, `operation ${operationLabel(op, path, method)}`),\n        pathLevelServers,\n        documentServers,\n      );\n\n      const {\n        operation,\n        inlineModels: opModels,\n        inlineModelBundles: opBundles,\n        envelopeCompanions: opCompanions,\n        operationQualifier,\n      } = buildOperation(\n        method,\n        path,\n        op,\n        pathLevelParams,\n        pathItem,\n        pathModelBaseName,\n        operationIdTransform,\n        serviceName,\n        componentSchemas,\n        componentParameters,\n        componentRequestBodies,\n        componentExamples,\n        componentHeaders,\n        componentResponses,\n        deferred,\n        apiRootLength,\n        servers,\n        refSiblingDescriptions,\n        componentResponseModelNames,\n        // Same \"METHOD /path\" key the operation resolver uses for the rest of the hint.\n        operationHints?.[`${method.toUpperCase()} ${path}`]?.pagination,\n        componentModels,\n        registry,\n      );\n      inlineModels.push(...opModels);\n      // The operation's models join the registry under its qualifier, so a\n      // later operation's items and every deferred schema step around them;\n      // its settled item models are already there (`typeInlineItems`).\n      registerInlineModels(registry, opModels, operationQualifier);\n      qualifierOf.set(operation, operationQualifier);\n      inlineModelBundles.push(...opBundles);\n      if (opCompanions) {\n        envelopeCompanions.push(...opCompanions);\n        for (const companion of opCompanions) companionQualifiers.set(companion, toPascalCase(operation.name));\n      }\n      // Same truthiness check as inferServiceName: for a tagged operation the\n      // service name *is* the normalized tag, so it doubles as the lookup key.\n      if (tag) tagServiceByOperation.set(operation, serviceName);\n      if (!op.operationId) pathNamed.add(operation);\n      const ops = serviceMap.get(serviceName) ?? [];\n      ops.push(operation);\n      serviceMap.set(serviceName, ops);\n    }\n  }\n\n  // Companion models of list envelopes are named once every list operation is\n  // known, so copies of one envelope shape can share a model. They take their\n  // final names before any deferred schema is named, so a fallback variant\n  // titled `ListMetadata` steps around the companion a primary response's\n  // `list_metadata` becomes, instead of the later merge keeping whichever has\n  // more fields under one name.\n  const companionFolds = new Map<EnvelopeCompanion, EnvelopeCompanion>();\n  const companionModels = resolveEnvelopeCompanionNames(envelopeCompanions, componentModels, companionFolds);\n  inlineModels.push(...companionModels);\n  // Each companion that kept its models is a site of its own, owning its\n  // envelope field and the envelope field of every operation whose copy\n  // folded onto it, so a merge pass that must rename one of its models (a\n  // deprecated companion named like a live component field's model, say)\n  // repoints every operation sharing it and nothing else.\n  inlineModelBundles.push(\n    ...companionBundles(envelopeCompanions, companionModels, companionFolds, companionQualifiers),\n  );\n\n  // Headers, secondary bodies, fallback bodies, error bodies and parameters\n  // are named last, in document order, against every name in the registry —\n  // the component models and enums, the components' field models, every\n  // request body, primary response, item and companion model — and against\n  // every enum name decided so far: the component enums, and every enum\n  // those models' fields or the operations' references — a parameter in any\n  // location, a body, a response of any kind, a response header, the\n  // pagination item type and envelope fields (`collectOperationTypeRefs`) —\n  // carry (an inline enum's `EnumRef`, named before the enum collector may\n  // rename it). An enum one of an operation's own references carries is\n  // registered as that operation's, so a deferred model of the operation\n  // that derives the name is qualified by location, as one that clashes\n  // with the operation's models is; a model's field enums are its\n  // operation's, a companion's no one's. So none of them takes a name one\n  // of those owns, whichever comes first in the document, and no model is\n  // ever named like an enum.\n  registerInlineModels(registry, companionModels);\n  for (const model of inlineModels) reserveEnumNames(registry, enumRefsOf(model), registry.get(model.name)?.operation);\n  for (const [op, qualifier] of qualifierOf) {\n    reserveEnumNames(registry, collectOperationTypeRefs(op).flatMap(collectEnumRefs), qualifier);\n  }\n  // An enum a deferred site itself types — a body that is an inline enum, or\n  // an array of one — is named only when the site is resolved, after the\n  // models of every site before it in the document; reserved now\n  // (`deferredEnumName`), a deferred object body of the same name steps\n  // past it whichever of the two the document declares first\n  // (`GetPetError404Body`), as it steps past every other enum in play, so a\n  // model never keeps an enum's name.\n  for (const item of deferred) {\n    const enumName = deferredEnumName(item);\n    if (enumName !== undefined) reserveEnumNames(registry, [enumName], item.operationQualifier);\n  }\n  const deferredTypes = resolveDeferredInlineTypes(deferred, registry);\n  inlineModels.push(...deferredTypes.models);\n  // The root every component-shared site wrote, by identity (every target of\n  // a site carries the one TypeRef its resolution produced), for the enum\n  // collector (`OperationExtractionResult.componentSites`).\n  const componentSites = new Set<TypeRef>();\n  for (const item of deferred) {\n    if (!item.componentSite) continue;\n    for (const target of item.targets) if (target.type) componentSites.add(target.type);\n  }\n  // Each deferred schema is a site of its own (the references it wrote, the\n  // models it minted). A reference any site wrote by sharing another site's\n  // model — a deferred body or header the registry matched to a primary\n  // body's model or a companion's, an array body's items it matched to an\n  // earlier operation's model — joins that site's roots, so a merge pass\n  // that renames the model (a deprecated copy named like a live one)\n  // repoints every response, header and array that shares it along with\n  // the site's own references.\n  inlineModelBundles.push(...deferredTypes.bundles);\n  attachSharedRefs(inlineModelBundles, new Set(registeredModels.map((model) => model.name)));\n\n  // The API root each operation's path sits under, for every step below: none\n  // for a tagged operation, whose service is its tag.\n  const rootLengthOf = (op: Operation) => (tagServiceByOperation.has(op) ? 0 : apiRootLengthOf(op.path, apiRoot));\n\n  // Split a tagged service whose tag groups operations from several first\n  // path segments — `/organizations` and `/organization_domains` both tagged\n  // `organizations` — into one service per segment. Decided over the tagged\n  // operations alone, so an untagged operation the service picked up by path\n  // never moves its tagged siblings (see splitTaggedServices).\n  splitTaggedServices(serviceMap, tagServiceByOperation);\n\n  // Disambiguate operation names within each service.\n  // Multiple operations can get the same name (e.g., several \"list\" endpoints\n  // in UserManagement for users, invitations, auth factors, etc.).\n  for (const [serviceName, operations] of serviceMap) {\n    disambiguateOperationNames(operations, pathNamed, serviceName, rootLengthOf);\n  }\n\n  const declaredTags = indexDocumentTags(documentTags);\n  const services: Service[] = Array.from(serviceMap.entries()).map(([name, operations]) => {\n    const { description, externalDocs } = resolveServiceDocs(name, operations, tagServiceByOperation, declaredTags);\n    // Omit each key entirely when no tag gives it so the IR shape is\n    // unchanged for documents without tag descriptions or links.\n    return {\n      name,\n      ...(description !== undefined ? { description } : {}),\n      ...(externalDocs !== undefined ? { externalDocs } : {}),\n      operations,\n    };\n  });\n\n  return { services, inlineModels, inlineModelBundles, componentSites };\n}\n\n/**\n * What a document tag contributes to the service it names. Both keys are\n * absent when the tag declares neither, so a declared-but-undocumented tag is\n * an empty record — still an entry in the index, which is what marks its\n * service as one that must not borrow another tag's wording.\n */\ninterface TagDocs {\n  description?: string;\n  externalDocs?: ExternalDocs;\n}\n\n/**\n * `base` with each doc field it lacks filled in from `extra`; a field `base`\n * already has is kept. The one rule for combining tag docs — among duplicate\n * tags in the index and among the tags a split-off service inherits from —\n * so `description` and `externalDocs` cannot resolve by different rules.\n */\nfunction fillMissingTagDocs(base: TagDocs, extra: TagDocs): TagDocs {\n  return { ...extra, ...base };\n}\n\n/**\n * Index the document's top-level `tags[]` by the service name each tag\n * produces, so a tag spelled `user_management`, `User Management`, or\n * `user-management` all map to the `UserManagement` service. Every named tag\n * is indexed — with its description when it declares a non-blank one, with\n * its `externalDocs` when it declares a usable one, and as an empty record\n * otherwise — because a declared-but-undocumented tag still marks its service\n * as one that must not borrow another tag's wording. When several tags\n * normalize to the same service name, each field is taken from the first of\n * them that gives it, so adding a link to one spelling never changes which\n * description the service shows.\n *\n * `parseSpec` ignored `tags` entirely before descriptions were read, so a\n * document with a malformed value — `tags` written as an object, a `null`\n * entry, a numeric `name` — used to parse and must keep parsing. Anything\n * that cannot be matched is skipped rather than thrown on, and a malformed\n * `externalDocs` is dropped the same way (see `readExternalDocs`).\n */\nfunction indexDocumentTags(documentTags: unknown): Map<string, TagDocs> {\n  const index = new Map<string, TagDocs>();\n  if (!Array.isArray(documentTags)) return index;\n  for (const tag of documentTags as unknown[]) {\n    if (typeof tag !== 'object' || tag === null) continue;\n    const { name, description, externalDocs } = tag as TagObject;\n    if (typeof name !== 'string' || name === '') continue;\n    const serviceName = toPascalCase(name);\n    const described = typeof description === 'string' && description.trim() !== '';\n    const docs: TagDocs = { ...(described ? { description } : {}), ...externalDocsEntry(externalDocs) };\n    index.set(serviceName, fillMissingTagDocs(index.get(serviceName) ?? {}, docs));\n  }\n  return index;\n}\n\n/**\n * Pick a service's docs — its `description` and `externalDocs` — from the\n * document's tags. Both fields go through this one path so they cannot\n * resolve to different tags by different rules.\n *\n * A service whose own name is a declared tag is documented by that tag alone:\n * its description and link when it has them, nothing otherwise. Another tag's\n * wording is never borrowed for it — operations tagged `api_keys` that the\n * path-prefix split merges into `UserManagement` must not label that service\n * \"API keys\".\n *\n * A service whose own name is not declared is one the split carved out of a\n * tag (e.g. `OrganizationDomains` from operations tagged `organizations`); it\n * inherits each field on its own from the first tag its operations carry that\n * gives it: the description of the first described tag, the link of the first\n * linked one, which need not be the same tag. Path-named services whose\n * operations have no tag carry nothing and stay undocumented.\n */\nfunction resolveServiceDocs(\n  serviceName: string,\n  operations: Operation[],\n  tagServiceByOperation: Map<Operation, string>,\n  declaredTags: Map<string, TagDocs>,\n): TagDocs {\n  const declared = declaredTags.get(serviceName);\n  if (declared !== undefined) return declared;\n  let docs: TagDocs = {};\n  for (const op of operations) {\n    const tagService = tagServiceByOperation.get(op);\n    if (tagService === undefined) continue;\n    const inherited = declaredTags.get(tagService);\n    if (inherited !== undefined) docs = fillMissingTagDocs(docs, inherited);\n  }\n  return docs;\n}\n\n/**\n * Words that mark where an API is mounted rather than naming a resource.\n * Deliberately tiny: `mountRules` regroup whatever this does not cover.\n */\nconst API_MARKER_SEGMENTS: ReadonlySet<string> = new Set(['api', 'rest']);\n\n/**\n * Whether a path segment marks the API root rather than naming a resource:\n * one of API_MARKER_SEGMENTS in any case, or a version such as `v1`,\n * `v2beta`, `1.0` or `2010-04-01`.\n */\nfunction isApiMarkerSegment(segment: string): boolean {\n  const lower = segment.toLowerCase();\n  return API_MARKER_SEGMENTS.has(lower) || /^v\\d/.test(lower) || /^\\d+([.-]\\d+)*$/.test(lower);\n}\n\n/** Leading literal segments of a path through its last API marker; `0` without one. */\nfunction pathRootLength(segments: readonly string[]): number {\n  let length = 0;\n  for (let i = 0; i < segments.length && !segments[i].startsWith('{'); i++) {\n    if (isApiMarkerSegment(segments[i])) length = i + 1;\n  }\n  return length;\n}\n\n/**\n * The API root the document's untagged operations sit under, as path\n * segments: `['api', 'v1']` for a document whose untagged paths all start\n * with `/api/v1/`, `[]` when there is none. Untagged operations skip it when\n * their service and fallback name are taken from the path.\n *\n * Each untagged operation's path contributes its own root — its leading\n * literal segments through the last API marker (see isApiMarkerSegment), so\n * `/api/v1/notes` contributes `api/v1`, `/wiki/rest/api/content` contributes\n * `wiki/rest/api`, `/api/user_management/users` contributes `api` alone and\n * `/api/{tenant}/notes` contributes `api`, a parameter ending the run. The\n * document root is the longest marker-terminated prefix shared, compared\n * verbatim, by every contribution that no other contribution extends:\n * `/api/v1/…` beside `/api/v2/…` gives `api`, and `/v1/…` beside `/v2/…`\n * gives nothing, so the two versions stay apart instead of merging into one\n * service per resource. A contribution that is a prefix of another —\n * `/api/openapi.json` or `/api/admin/users` beside `/api/v1/notes` — does not\n * shorten the root to `api` for every path: it skips only its own `api`\n * (see apiRootLengthOf), and `/api/v1/notes` stays `Notes` rather than\n * landing in `V1`. Only a second version disagrees with the first, and that\n * alone is what needs the shorter root.\n *\n * A path with no marker at all (`/health`, `/openapi.json`) contributes\n * nothing: it sits outside any root and keeps its own first segment, and it\n * does not switch the root off for the rest of the document (see\n * apiRootLengthOf). A shared prefix without a marker is therefore kept whole\n * — `/user_management/users` and `/user_management/invitations` stay one\n * `UserManagement` service — because a module prefix every path shares is\n * the service, not noise, and nothing but the word tells it from `/api`.\n * Tagged operations never take part, since only path-named services use the\n * root; nor do path items that declare no operation.\n */\nfunction documentApiRoot(paths: Record<string, PathItem>): string[] {\n  const contributions: string[][] = [];\n  for (const [path, pathItem] of Object.entries(paths)) {\n    // Same read as the service naming above: a first usable tag names the service.\n    const hasUntaggedOperation = HTTP_METHODS.some((method) => {\n      const op = pathItem[method];\n      return Boolean(op) && extractTags(op?.tags) === undefined;\n    });\n    if (!hasUntaggedOperation) continue;\n    const segments = pathSegments(path);\n    const own = segments.slice(0, pathRootLength(segments));\n    if (own.length > 0) contributions.push(own);\n  }\n  // Every strict prefix of a contribution, so a contribution another one\n  // extends can be left out. Segments never contain `/`, so the join is exact.\n  const extended = new Set<string>();\n  for (const own of contributions) {\n    for (let length = 1; length < own.length; length++) extended.add(own.slice(0, length).join('/'));\n  }\n  let root: string[] | undefined;\n  for (const own of contributions) {\n    if (extended.has(own.join('/'))) continue;\n    if (root === undefined) {\n      root = own;\n      continue;\n    }\n    root = root.slice(0, sharedPrefixLength(root, own));\n  }\n  if (root === undefined) return [];\n  return root.slice(0, pathRootLength(root));\n}\n\n/** How many leading segments two paths share, compared verbatim. */\nfunction sharedPrefixLength(a: readonly string[], b: readonly string[]): number {\n  let shared = 0;\n  while (shared < a.length && shared < b.length && a[shared] === b[shared]) shared++;\n  return shared;\n}\n\n/**\n * How many leading segments of a path are the document's API root: as much\n * of the path's own root (pathRootLength) as the document root shares,\n * compared verbatim. For a path that starts with the whole root that is the\n * root's length; for one that stops short of it — `/api/openapi.json` under a\n * root of `api/v1` — it is the path's own `api`, skipped for that path alone;\n * and `0` for a path outside the root, which is named as if the document had\n * none. The two roots are prefixes of one contribution whenever the path is\n * untagged, so what they share always ends on a marker.\n */\nfunction apiRootLengthOf(path: string, apiRoot: readonly string[]): number {\n  const segments = pathSegments(path);\n  return sharedPrefixLength(apiRoot, segments.slice(0, pathRootLength(segments)));\n}\n\n/**\n * Index of the segment a path-named service takes its name from, among the\n * segments readPath reads. Under an API root it is the first literal segment\n * after the root, so `/v1/notes` and `/v1/{teamId}/notes` both name `Notes`;\n * when nothing literal follows the root, the first segment, so `/api` and\n * `/api/{id}` name `Api` as they always did rather than `Default`. The\n * fallback operation name skips the same segment (see inferResourceFromPath),\n * so it is never echoed as `Api.getApi`.\n *\n * The verb of a custom method is not a resource and never names a service:\n * `/v1/{name}:cancel` stays in `V1` beside `/v1/{name}`, and `/api/v1:reset`\n * lands in `Api`, where the slash-written `/v1/{name}/cancel` names\n * `Cancel`. The resource it is written on is still found first when there is\n * one, so `/v1/pets:batchGet` names `Pets` like `/v1/pets`.\n *\n * Without a root (`apiRootLength` of 0: a root-less document, a path outside\n * the root, or a tagged operation) it is always the first segment, parameter\n * or not, so every such operation is named exactly as before this rule\n * existed: an untagged `/{tenant}/users` stays `Default.listUsers`.\n */\nfunction serviceSegmentIndex(path: string, apiRootLength: number): number {\n  if (apiRootLength === 0) return 0;\n  const index = readPath(path).findIndex(\n    (segment, i) => i >= apiRootLength && !segment.text.startsWith('{') && !segment.customMethod,\n  );\n  return index === -1 ? 0 : index;\n}\n\n/**\n * The service an operation belongs to: its first tag, else a path segment.\n *\n * The path fallback takes the first literal segment after the API root the\n * document sits under (`apiRootLength`, see documentApiRoot): `/widgets/{id}/sub`\n * is `Widgets`, and so are `/api/widgets` and `/api/{tenant}/widgets` when the\n * root is `/api`, instead of the whole API collapsing into one `Api` service.\n * When nothing literal follows the root — the path is the root itself, or\n * only parameters come next — the first segment names the service as it\n * always did, so `/api` and `/api/{id}` land in `Api` rather than in `Default`.\n * The verb of a custom method is read past (see serviceSegmentIndex), so\n * `/v1/{name}:cancel` lands in `V1` as well.\n */\nfunction inferServiceName(path: string, tag: string | undefined, apiRootLength: number): string {\n  // Prefer OpenAPI tag when available — tags represent the logical grouping\n  // (e.g., \"multi-factor-auth\" for /auth/factors/* endpoints).\n  if (tag) {\n    return toPascalCase(tag);\n  }\n  const first = pathSegments(path)[serviceSegmentIndex(path, apiRootLength)] ?? 'Default';\n  // Skip path params\n  if (first.startsWith('{')) return 'Default';\n  return toPascalCase(first);\n}\n\n/**\n * The service a tagged operation is split off to, named from its first path\n * segment: `/organization_domains/{id}` → `OrganizationDomains`. A path whose\n * first segment is a parameter, or that has no segment at all (`/`), has\n * nothing to be split on and names the service it is already in, so\n * `/{tenant}/notes` beside `/notes` under one tag stays put.\n */\nfunction splitSegmentService(op: Operation, serviceName: string): string {\n  const first = pathSegments(op.path)[0];\n  return first === undefined || first.startsWith('{') ? serviceName : toPascalCase(first);\n}\n\n/**\n * The service an operation lands in once the service it was grouped under\n * (`serviceName`: its tag, else the segment its path named) is known in full.\n *\n * A tagged operation moves to the service its own first segment names (see\n * splitSegmentService) only when the operations carrying its tag sit under\n * more than one first segment — `segmentServices`, the first-segment services\n * of that service's tagged operations alone. A tag whose operations all share\n * one first segment keeps them together even when that segment is not the\n * tag: `/api/v1/notes` tagged `notes` stays in `Notes`, not `Api`.\n *\n * An untagged operation keeps the service its path named: the segment it\n * would be split on is the one it was named from, so it can neither cause\n * nor prevent a split, nor be moved by one.\n */\nfunction resolveServiceName(\n  op: Operation,\n  serviceName: string,\n  tagged: boolean,\n  segmentServices: ReadonlySet<string>,\n): string {\n  if (!tagged || segmentServices.size <= 1) return serviceName;\n  return splitSegmentService(op, serviceName);\n}\n\n/**\n * Split each service whose tag groups operations from several first path\n * segments into one service per segment: `/organizations` and\n * `/organization_domains` both tagged `organizations` become `Organizations`\n * and `OrganizationDomains`. A part named like a service that already exists\n * — another tag's, or one named from a path — joins it.\n *\n * Every operation's destination is decided by resolveServiceName from the\n * grouping as it stands before any service is split, over each service's\n * tagged operations alone. So an untagged operation a tagged service picked\n * up by path — `/api/v1/notes/{noteId}/export` beside `/api/v1/notes` tagged\n * `notes` — does not add a second segment to the tag's set and move the\n * tagged operations into `Api` (issue #287), and operations a split moves\n * into another tag's service do not add a segment to that tag's set either,\n * whichever service the document lists first.\n *\n * Mutates `serviceMap`: a split service is removed and each of its parts is\n * appended under its own name, or merged into the existing service of that\n * name, in the order the parts first appear.\n */\nfunction splitTaggedServices(\n  serviceMap: Map<string, Operation[]>,\n  tagServiceByOperation: ReadonlyMap<Operation, string>,\n): void {\n  const plan = new Map<string, ServiceSplit>();\n  for (const [serviceName, operations] of serviceMap) {\n    const segmentServices = new Set<string>();\n    for (const op of operations) {\n      if (tagServiceByOperation.has(op)) segmentServices.add(splitSegmentService(op, serviceName));\n    }\n    const parts = new Map<string, Operation[]>();\n    for (const op of operations) {\n      const name = resolveServiceName(op, serviceName, tagServiceByOperation.has(op), segmentServices);\n      const part = parts.get(name) ?? [];\n      part.push(op);\n      parts.set(name, part);\n    }\n    plan.set(serviceName, { operations, own: operations.length, parts });\n  }\n  for (const [serviceName, { operations, own, parts }] of plan) {\n    if (parts.size <= 1) continue;\n    // Parts of services split before this one that joined it were appended to\n    // its array after the plan was read. They resolved to this service's name,\n    // so they stay in the part that keeps it instead of going with the array.\n    const joined = operations.slice(own);\n    if (joined.length > 0) parts.set(serviceName, [...(parts.get(serviceName) ?? []), ...joined]);\n    serviceMap.delete(serviceName);\n    for (const [name, ops] of parts) {\n      const existing = serviceMap.get(name) ?? [];\n      existing.push(...ops);\n      serviceMap.set(name, existing);\n    }\n  }\n}\n\n/** One service's split, planned from the grouping before any service is split (see splitTaggedServices). */\ninterface ServiceSplit {\n  /** The service's operations: the array `serviceMap` holds, which parts of services split earlier may join. */\n  operations: Operation[];\n  /** How many of `operations` the plan was read from; any beyond them joined since. */\n  own: number;\n  /** The service each operation moves to, with its operations in document order; one entry when nothing moves. */\n  parts: Map<string, Operation[]>;\n}\n\n/**\n * Strip overload indices (e.g. NestJS emits `Foo_bar[0]` when a controller\n * method handles multiple routes) from an operationId so derived names never\n * leak the bracketed digit. Without this, `authenticate[0]` would surface as\n * `authenticate0` in method names and `Authenticate0Request` in body model\n * names. Brackets at the end (or with trailing whitespace) are common in\n * NestJS-style backends; this regex is intentionally narrow to avoid eating\n * legitimate digits like `oauth2`.\n */\nfunction normalizeOperationIdForNaming(operationId: string): string {\n  return operationId.replace(/\\[\\d+\\]\\s*$/, '');\n}\n\n/**\n * The inline request body, response or error body model name of an operation\n * that has an `operationId`. The single source of that name: extractRequestBody,\n * deriveResponseName, deriveFallbackResponseName and deriveErrorModelName use\n * it to name, resolvePathModelBaseNames to reserve.\n */\nfunction operationIdModelName(operationId: string, suffix: string): string {\n  return cleanSchemaName(toPascalCase(normalizeOperationIdForNaming(operationId)) + suffix);\n}\n\n/**\n * The stem every model derived from an `operationId` starts with: its\n * `Request`, `Response` and `Error<code>` models, a list's `Item`, nested\n * inline models under those (`…ResponseOwner`) and envelope companions\n * (`…ListMetadata`). Every step of cleanSchemaName is a global replace or acts\n * on the leading word, so this is a true prefix of each of those names. Used\n * to reserve them all.\n */\nexport function operationIdModelBase(operationId: string): string {\n  return cleanSchemaName(toPascalCase(normalizeOperationIdForNaming(operationId)));\n}\n\nfunction inferOperationName(\n  method: HttpMethod,\n  path: string,\n  operationId?: string,\n  operationIdTransform?: (id: string) => string,\n  apiRootLength = 0,\n): string {\n  if (operationId) {\n    const normalized = normalizeOperationIdForNaming(operationId);\n    if (operationIdTransform) {\n      return operationIdTransform(normalized);\n    }\n    return toCamelCase(normalized);\n  }\n\n  // Fallback when no operationId is available — use method + path to build\n  // a descriptive name like \"listUsers\", \"getOrganization\", \"deleteAuthFactor\",\n  // \"getPetStatus\" for a singleton of one item, or \"adoptPet\" for an action.\n  return fallbackOperationName(method, path, apiRootLength);\n}\n\n/**\n * The name of an operation without an `operationId`, built from its method\n * and path. Three shapes, tried in this order:\n *\n *   - an action (inferAction): the action segment is the verb phrase and\n *     its resource follows — `POST /store/pets/{id}/adopt` is `adoptPet`,\n *     `DELETE /store/pets/bulk-delete` is `bulkDeletePets`, and\n *     `DELETE /pets/bulk-delete` in `Pets` is the bare `bulkDelete`;\n *   - a singleton of one item (inferSingleton): the method's item verb\n *     (inferVerb), the singular parent and the segment —\n *     `GET /store/pets/{id}/status` is `getPetStatus`;\n *   - otherwise the CRUD verb (inferVerb) plus the resource noun\n *     (inferResourceFromPath), singular for an item operation —\n *     `GET /store/pets/{id}` is `getPet` — or the verb alone when the path\n *     names no resource past the service segment: `GET /pets/{id}` in `Pets`\n *     is `get`.\n *\n * The parts of an action or singleton name are joined by appendQualifier,\n * so a word is never repeated across a join:\n * `GET /companies/verification/{id}/verification-status` is\n * `getVerificationStatus`.\n *\n * `actions` false skips the first shape, for an operation that gave an\n * action name up to another method on its path (demoteSamePathNames):\n * `POST /pets/bulk-delete` is then `createBulkDelete`.\n */\nfunction fallbackOperationName(method: HttpMethod, path: string, apiRootLength: number, actions = true): string {\n  const action = actions ? inferAction(method, path, apiRootLength) : null;\n  if (action) return appendQualifier(toCamelCase(action.verb), action.resource);\n  const singleton = inferSingleton(path, apiRootLength);\n  if (singleton) {\n    return appendQualifier(appendQualifier(inferVerb(method, path), singleton.parent), singleton.resource);\n  }\n  const verb = inferVerb(method, path);\n  const resource = inferResourceFromPath(path, apiRootLength);\n  return resource ? toCamelCase(`${verb}_${resource}`) : verb;\n}\n\n/**\n * The name fallbackOperationName gave an item operation before its resource\n * was singularised: the resource as the path spells it, `getPets` for\n * `GET /store/pets/{id}`. `null` for an action (inferAction) and for a\n * singleton (inferSingleton), whose names are not built from a singularised\n * resource, and for an operation whose resource is not singularised — a\n * collection, a path with no resource, a segment that does not look plural —\n * so a non-null result always differs from the singular name.\n * disambiguateOperationNames falls back to it before a numeric suffix when\n * the singular name is an operationId's, or another path-named operation's\n * whose path differs only by that plural. `actions` is fallbackOperationName's.\n */\nfunction pluralFallbackName(method: HttpMethod, path: string, apiRootLength: number, actions = true): string | null {\n  if ((actions && inferAction(method, path, apiRootLength)) || inferSingleton(path, apiRootLength)) return null;\n  const resource = inferResourceFromPath(path, apiRootLength, false);\n  if (resource === null || resource === inferResourceFromPath(path, apiRootLength)) return null;\n  return toCamelCase(`${inferVerb(method, path)}_${resource}`);\n}\n\n/**\n * The CRUD verb each HTTP method takes on one item and on a collection. Only\n * GET's differ: `get` for one item, `list` for a collection.\n */\nconst METHOD_VERBS: Record<HttpMethod, { readonly item: string; readonly collection: string }> = {\n  get: { item: 'get', collection: 'list' },\n  post: { item: 'create', collection: 'create' },\n  put: { item: 'update', collection: 'update' },\n  patch: { item: 'update', collection: 'update' },\n  delete: { item: 'delete', collection: 'delete' },\n  head: { item: 'check', collection: 'check' },\n  options: { item: 'options', collection: 'options' },\n  trace: { item: 'trace', collection: 'trace' },\n};\n\n/**\n * The verbs a POST on a literal with no parameter before it is read as an\n * action phrase by, when one of them is the segment's last word\n * (inferAction): the CRUD verbs of METHOD_VERBS. `options` and `trace` are\n * left out, since `/settings/display-options` names a collection.\n */\nconst CRUD_VERBS: ReadonlySet<string> = new Set(['get', 'list', 'create', 'update', 'delete', 'check']);\n\n/**\n * The verbs that count as a method's own only as the first word of a segment\n * (segmentCarriesVerb): `list-all` and `check-health` do something, while as\n * a later word `list` and `check` name a thing — `wish-list`, `allow-list`,\n * `health-check`. Every other verb counts in any position: `bulk-delete`,\n * `batch-get`, `force-update`, `auto-create`.\n */\nconst LEADING_ONLY_VERBS: ReadonlySet<string> = new Set(['list', 'check']);\n\n/**\n * Infer the CRUD verb from the HTTP method and the path shape (METHOD_VERBS):\n * the item verb when the path addresses one item — it ends in a path\n * parameter, or in a singleton of the item before it (isSingletonSegment) —\n * and the collection verb otherwise. `GET /pets/{id}` and\n * `GET /pets/{id}/status` are `get`; `GET /pets` and `GET /pets/{id}/photos`\n * are `list`. Not consulted for an action (inferAction), whose verb is the\n * action segment itself.\n */\nfunction inferVerb(method: HttpMethod, path: string): string {\n  const segments = pathSegments(path);\n  const last = segments[segments.length - 1];\n  const item = last !== undefined && (last.startsWith('{') || isSingletonSegment(segments));\n  return item ? METHOD_VERBS[method].item : METHOD_VERBS[method].collection;\n}\n\n/** The verbs inferVerb can give a method: `get` and `list` for GET, one verb for every other. */\nfunction methodVerbs(method: HttpMethod): string[] {\n  const verbs = METHOD_VERBS[method];\n  return verbs.item === verbs.collection ? [verbs.item] : [verbs.item, verbs.collection];\n}\n\n/**\n * Whether the last segment of a path is a literal whose words include one of\n * the method's own verbs (methodVerbs): `bulk-delete` for a DELETE, `list-all`\n * and `batch-get` for a GET, `update-password` for a PUT or PATCH, and not\n * `bulk-delete` for a POST. `list` and `check` count only as the first word\n * (LEADING_ONLY_VERBS), so `wish-list`, `allow-list` and `health-check` carry\n * no verb. Such a segment is the action for that method (inferAction) and\n * keeps the action name when another method on the path would take it too\n * (demoteSamePathNames).\n */\nfunction segmentCarriesVerb(method: HttpMethod, path: string): boolean {\n  const segments = pathSegments(path);\n  const last = segments[segments.length - 1];\n  if (last === undefined || last.startsWith('{')) return false;\n  const words = splitWords(last).map((w) => w.toLowerCase());\n  return methodVerbs(method).some((verb) => (LEADING_ONLY_VERBS.has(verb) ? words[0] === verb : words.includes(verb)));\n}\n\n/** Whether a path segment looks plural: singularizePathSegment would change it. */\nfunction looksPlural(segment: string): boolean {\n  return singularizePathSegment(segment) !== segment;\n}\n\n/**\n * Whether the last segment is a singleton of the item before it: a literal\n * that follows a path parameter and does not look plural (looksPlural), so it\n * names one thing about that item — `status` in `/pets/{id}/status`, `avatar`\n * in `/users/{id}/avatar` — rather than a nested collection of it\n * (`/pets/{id}/photos`, `/orgs/{id}/api_keys`).\n */\nfunction isSingletonSegment(segments: readonly string[]): boolean {\n  if (segments.length < 2) return false;\n  const last = segments[segments.length - 1];\n  return !last.startsWith('{') && segments[segments.length - 2].startsWith('{') && !looksPlural(last);\n}\n\n/**\n * The noun a literal path segment contributes to an operation name. A\n * segment a path parameter follows addresses one item of its collection, so\n * it is singular (`singularizePathSegment`): `pets` in `/store/pets/{id}` is\n * `pet`. Any other segment is kept as the path spells it: `pets` in\n * `/store/pets`, `legacy` in `/users/{id}/legacy/factors`. The one rule for\n * the resource (inferResourceFromPath), the segments between the service and\n * the resource (inferDeeperContext) and the service noun a name restores\n * (inferServiceNoun), so `/store/cats/{id}/toys/{toyId}` and\n * `/api/notes/{noteId}` read `Cat` and `Note`, as `/store/pets/{id}` reads\n * `Pet`. The parent of an action or a singleton (inferItemParent) is singular\n * by that function's own rule, which does not look at the segment after it.\n */\nfunction pathSegmentNoun(segments: readonly string[], index: number): string {\n  const segment = segments[index];\n  return segments[index + 1]?.startsWith('{') ? singularizePathSegment(segment) : segment;\n}\n\n/**\n * Extract a resource noun from the path for operation naming.\n * Uses the last non-param segment (the resource being operated on). An item\n * operation — the last literal segment is followed by a path parameter —\n * addresses one entity, so its noun is singularised (pathSegmentNoun).\n *\n * Examples:\n *   /accounts/users → \"Users\"\n *   /accounts/users/{id} → \"User\" (singular for item operations)\n *   /accounts/users/{id}/auth_factors → \"AuthFactors\"\n *   /accounts/users/{id}/auth_factors/{factor_id} → \"AuthFactor\"\n *   /organizations/{id}/api_keys → \"ApiKeys\"\n *   /auth/authorize → \"Authorize\" (action endpoint)\n *   /teams/{id}/teams → \"Teams\" (the teams under one team, in `Teams`)\n *   /teams → null (the segment the service was named from)\n *\n * `apiRootLength` is the document's API root the path sits under (see\n * documentApiRoot); the service segment is the first literal one after it.\n * `singularItem` false keeps an item's noun as the path spells it (`Users`\n * for `/accounts/users/{id}`), for pluralFallbackName.\n */\nfunction inferResourceFromPath(path: string, apiRootLength = 0, singularItem = true): string | null {\n  const segments = pathSegments(path);\n  if (segments.length <= 1) return null;\n\n  // Find the last meaningful (non-param) segment past the API root, so a\n  // root word is never the resource: /api/v1/{id} is Api.delete, not deleteV1.\n  let resourceIndex = -1;\n  for (let i = segments.length - 1; i >= apiRootLength; i--) {\n    if (!segments[i].startsWith('{')) {\n      resourceIndex = i;\n      break;\n    }\n  }\n\n  if (resourceIndex < 0) return null;\n  // Skip the segment the service was named from, compared by position — it\n  // would be redundant: /api/notes is Notes.list, not Notes.listNotes. A\n  // later segment that spells the same word names a resource of its own:\n  // /teams/{id}/teams in Teams is listTeams, the teams under one team, and\n  // never the bare `list` that reads as the service collection.\n  if (resourceIndex === serviceSegmentIndex(path, apiRootLength)) return null;\n\n  return toPascalCase(singularItem ? pathSegmentNoun(segments, resourceIndex) : segments[resourceIndex]);\n}\n\n/**\n * Index of the parent of a path's last segment, when that segment follows a\n * path parameter: the nearest literal before the parameter that is past the\n * document's API root (`apiRootLength`, see documentApiRoot) and is not an\n * API marker (isApiMarkerSegment) — the marker check also covers a tagged\n * operation, which has no root. `pets` in `/pets/{petId}/adopt` and in\n * `/owners/{o}/pets/{p}/vaccinate`; `-1` when no such literal exists, as in\n * `/api/v1/{companyId}/sendDocument` and `/{id}/adopt`. The parent is kept\n * even when it is the service segment: `/pets/{id}/archive` in `Pets` is\n * `archivePet` and `/pets/{id}/status` is `getPetStatus`, the names they\n * have under `/admin` in `Admin` too, so a name never depends on where the\n * service boundary falls.\n */\nfunction itemParentIndex(segments: readonly string[], apiRootLength: number): number {\n  for (let i = segments.length - 3; i >= apiRootLength; i--) {\n    if (!segments[i].startsWith('{') && !isApiMarkerSegment(segments[i])) return i;\n  }\n  return -1;\n}\n\n/**\n * The parent of a path's last segment (itemParentIndex) as a noun, singular\n * since the parameter addresses one of it: `Pet` for `/pets/{petId}/adopt`.\n * `null` when there is none.\n */\nfunction inferItemParent(segments: readonly string[], apiRootLength: number): string | null {\n  const index = itemParentIndex(segments, apiRootLength);\n  return index < 0 ? null : toPascalCase(singularizePathSegment(segments[index]));\n}\n\n/**\n * Recognise a singleton of one item (isSingletonSegment) and the two nouns\n * its name is built from: the singular parent (inferItemParent) and the\n * segment itself, `Pet` and `Status` for `/pets/{id}/status`, which\n * fallbackOperationName joins after the method's item verb: `getPetStatus`,\n * `updatePetStatus`, `deletePetStatus`, `checkPetStatus`, and\n * `createOrderStatus` for `POST /orders/{id}/status`. A POST on a singleton\n * that does not end in `s` is an action instead (inferAction), so\n * `/users/{id}/avatar` is `getUserAvatar` for a GET but `avatarUser` for a\n * POST; give the POST an `operationId`.\n */\nfunction inferSingleton(path: string, apiRootLength = 0): { parent: string | null; resource: string } | null {\n  const segments = pathSegments(path);\n  if (!isSingletonSegment(segments)) return null;\n  return {\n    parent: inferItemParent(segments, apiRootLength),\n    resource: toPascalCase(segments[segments.length - 1]),\n  };\n}\n\n/**\n * Recognise an action: the last segment is a literal that names what the\n * operation does rather than a resource, so it is the whole verb phrase of\n * the name and the method's CRUD verb is left off. Three shapes:\n *\n *   - a POST on a literal that follows a path parameter and does not end in\n *     `s`: `/pets/{petId}/adopt`, `/owners/{o}/pets/{p}/vaccinate`. A literal\n *     ending in `s` after the parameter is a nested collection to create into\n *     (`/orgs/{id}/api_keys`) or a singleton of the item (`/orders/{id}/status`,\n *     see inferSingleton), and keeps `create`;\n *   - for any method, a literal that carries the method's own verb\n *     (segmentCarriesVerb), which the name would otherwise repeat:\n *     `bulk-delete` on a DELETE, `list-all` on a GET, `update-password` on a\n *     PUT after a parameter. A literal that carries another method's verb is\n *     not: after a parameter it is a singleton, `GET /users/{id}/last-update`\n *     is `getUserLastUpdate`, and before none it is a collection,\n *     `GET /pets/update` is `listUpdate` and `GET /pets/last-update` is\n *     `listLastUpdate`;\n *   - a POST on a literal with no parameter before it whose last word is any\n *     CRUD verb (CRUD_VERBS): `POST /pets/bulk-delete`, `POST /users/bulk-update`,\n *     `POST /v1/pets:batchGet`. Such a literal is otherwise read as a\n *     collection (`/pets/search` is `createSearch`), which would make it\n *     `createBulkDelete`. The last word only, so `/pets/delete-candidates`\n *     stays a collection, and a POST only, since a verb that is not the\n *     method's own is not what the method does.\n *\n * The verb is the segment itself. The resource is the singular parent\n * (inferItemParent) when the segment follows a parameter — `adopt` + `Pet` —\n * and otherwise the collection the segment sits under, as\n * inferResourceFromPath reads the path without the segment, so\n * `/pets/bulk-delete` in `Pets` is the bare `bulkDelete` and\n * `/store/pets/bulk-delete` is `bulkDeletePets`. The caller leaves the\n * resource off when the verb already ends with it (`restart-id-verification`\n * under `verification` is `restartIdVerification`, see appendQualifier).\n *\n * A custom method written after a colon is read as the segment it is written\n * on followed by the verb (see pathSegments): `/pets/{petId}:adopt` is\n * `{petId}` then `adopt`, so it is the action `adoptPet` exactly as\n * `/pets/{petId}/adopt` is; `/pets:bulkDelete` is read as `/pets/bulkDelete`\n * and is `bulkDelete`; `/pets:search` is read as `/pets/search` and stays a\n * `create`.\n */\nfunction inferAction(\n  method: HttpMethod,\n  path: string,\n  apiRootLength = 0,\n): { verb: string; resource: string | null } | null {\n  const segments = pathSegments(path);\n  if (segments.length === 0) return null;\n  const last = segments[segments.length - 1];\n  if (last.startsWith('{')) return null;\n  const afterParam = segments.length >= 2 && segments[segments.length - 2].startsWith('{');\n  const words = splitWords(last).map((w) => w.toLowerCase());\n  const postAction = method === 'post' && afterParam && !last.toLowerCase().endsWith('s');\n  const ownVerb = segmentCarriesVerb(method, path);\n  const verbPhrase = method === 'post' && !afterParam && words.length > 0 && CRUD_VERBS.has(words[words.length - 1]);\n  if (!postAction && !ownVerb && !verbPhrase) return null;\n\n  const resource = afterParam\n    ? inferItemParent(segments, apiRootLength)\n    : inferResourceFromPath('/' + segments.slice(0, -1).join('/'), apiRootLength);\n  return { verb: last, resource };\n}\n\n/**\n * Detect and resolve name collisions within a service's operations.\n *\n * A name taken from an `operationId` is the author's choice and is never\n * rewritten here. A name derived from the method and path (inferOperationName)\n * is only as unique as the path words it was built from, so when operations on\n * different paths share one, the path-named operations are qualified until\n * every path in the service has a name of its own. Operations on one path\n * share a name only when both are path-named and their methods take the same\n * CRUD verb (PUT and PATCH both `update`); any other sharing on one path is\n * resolved first (demoteSamePathNames), before the qualifiers below, since\n * every consumer that keys a service's operations by name — the differ among\n * them — would otherwise see one of the two. An action that shares a name\n * with a path-named operation of another shape yields next\n * (yieldActionNames), so `update` stays with `PUT /pets/{id}` and\n * `POST /pets/update` is `updatePets`. A name any pass gives an operation is\n * checked against every name the service holds, and once every pass has run\n * the one-path rule is checked once more (numberSamePathNames), since a\n * rename can land on a name an operation on the same path already has.\n *\n * `apiRootLengthOf` gives the API root each operation's path sits under (see\n * documentApiRoot), so neither the resource nor the deeper context echoes the\n * root or the service segment into a name: `DELETE /api/v1/notes/all` in\n * `Notes` is `deleteAll`, never `deleteAllV1Notes`. An action's resource and\n * deeper context are read from its path without the action segment, and a\n * singleton's without its parent (see qualifierPath), so a second `adoptPet`\n * or `getPetStatus` is qualified by what sets its path apart and never by\n * repeating `Adopt` or `Pet`.\n *\n * Qualifiers are tried in order, each on every group still colliding after\n * the one before, and every pass — the qualifiers, the plural and nothing\n * else — goes through one rule, qualifyGroup: a pass renames a group's\n * path-named members only when the names it proposes tell the group apart,\n * and a context two paths write alike is spelled alike for both (see the\n * deeper-context qualifier), so a qualifier the colliding paths all carry —\n * `Teams` in `/org/teams/members` and `/org/teams/{teamId}/members`, written\n * once, singular after `{teamId}` — is never added, and the next pass tells\n * them apart: `listMembers` and `listMembersByTeamId`; a proposal\n * another operation already has is not taken, so a pass never hands a member\n * a name another operation had with the number then landing on it\n * (`/org/members/archived` beside `/org/archived_members` is never\n * `listArchivedMembers2`, and `/api/notes` beside `operationId: listNotes` is\n * never `listNotes2`) — unless every operation that has it is path-named and\n * names the same noun, which the member then joins (nameIsFree): `/notes`\n * restoring `Notes` beside `/notes/{noteId}/notes` is `listNotes` with the\n * nested collection `listNotesByNoteId`; and members whose proposals say the\n * same thing take one spelling and stay one group for the next pass, numbered\n * on it when nothing after tells them apart. A qualifier never puts the\n * same word twice in a row into a name, whether the name already ends with it\n * (`listNotes` never becomes `listNotesNotes`) or the qualifier repeats it\n * itself (`/api/analytics/analytics/teams` → `listTeamsAnalytics`), compared\n * word by word on the camelCase boundary rather than as a substring:\n *\n *   1. the resource noun (inferResourceFromPath); for the service's own\n *      path, whose plain name left that noun off, the service noun\n *      (inferServiceNoun) when a path-named operation outside the group\n *      already carries it under the name it would make, so that `/notes`\n *      beside `operationId: list` joins `/notes/{noteId}/notes` at\n *      `listNotes` and the parameter then tells them apart;\n *   2. the path segments between the service and the resource\n *      (inferDeeperContext), each singular when a path parameter follows it\n *      (pathSegmentNoun): `GET /users/{id}/legacy/factors` next to\n *      `GET /users/{id}/factors` → `listFactorsLegacy`, and\n *      `GET /store/cats/{id}/toys/{toyId}` next to\n *      `GET /store/dogs/{id}/toys/{toyId}` → `getToyCat` and `getToyDog`.\n *      A path whose singular spelling would take the name of an operation\n *      outside the group, or of another path in the group that the\n *      spelling as written sets apart, keeps the segments as written, the\n *      plural being what tells them apart: `/store/pets/{id}/toys/{toyId}`\n *      next to `/store/pet/{id}/toys/{toyId}` → `getToyPets` and\n *      `getToyPet`, and `/store/cats/{id}/toys/{toyId}` next to\n *      `operationId: getToyCat` → `getToyCats`;\n *   3. `By<Param>` for each path parameter the colliding paths do not all\n *      share, in path order, when those are what tell the paths apart:\n *      `GET /v1/notes` keeps `list` while `GET /v1/{teamId}/notes` becomes\n *      `listByTeamId`, with no root `GET /users/teams` keeps `listTeams` while\n *      `GET /users/{id}/teams` becomes `listTeamsById`, and\n *      `GET /api/notes/{noteId}` keeps `get` while\n *      `GET /api/{teamId}/notes/{noteId}` becomes `getByTeamId`, the shared\n *      `noteId` adding nothing;\n *   4. the API root words a path skipped beyond those the colliding rooted\n *      paths all skipped, when the paths sit under different lengths of the\n *      document root: `GET /api/notes` keeps `list` while `GET /api/v1/notes`\n *      becomes `listV1`. A root-less path takes no part;\n *   5. the resource noun the plain name left off because it names the\n *      service (inferServiceNoun), when the colliding paths do not all drop\n *      the same one. This is what tells a path-named operation from an\n *      operationId it collides with, which is never renamed and which the\n *      parameters above cannot touch: `GET /api/notes` beside\n *      `operationId: list` on `GET /api/{teamId}/notes` is `listNotes`;\n *   6. for a path-named item operation whose singular name none of those\n *      could tell apart — `GET /store/pets/{id}` is `getPet`, and so is\n *      `operationId: getPet` on `/store/featured/{id}`, or path-named\n *      `GET /store/pet/{id}`, whose path differs only by the plural the\n *      singular erased — the plural name it had before item resources were\n *      singularised, `getPets` (pluralFallbackName), when no operation\n *      outside the group has it. The plural still says which collection is\n *      read, and it is the name every SDK generated from such a document\n *      already exposes, where a number says nothing. Like the qualifiers\n *      above it runs only when it tells the group apart: an operationId-named\n *      operation, an action, a singleton and a name a qualifier has already\n *      extended have no plural, so any member that has one differs from\n *      them, while a group whose members would all take the same plural\n *      (`/store/Pets/{id}` beside `/store/pets/{id}`) goes straight to the\n *      suffix, since `getPets` beside `getPet` would say nothing about\n *      which is which. Members that share a plural some other member does\n *      not take it together and are numbered on it: beside `/store/pet/{id}`\n *      or an operationId's `getPet`, those two are `getPets` and `getPets2`,\n *      each a variant of its twin rather than of the operationId;\n *   7. a numeric suffix (`listNotes2`, `listNotes3`, …), when no pass above\n *      has a free name that tells the group apart, so an emitter never\n *      sees two methods with one name in one class. A name that already\n *      ends in a digit — the version the root words gave it (`listV1`), a\n *      path word (`listTop10`), an operationId (`getV2`) — takes the number\n *      behind `No` (numberedName): `GET /api/v1` beside `GET /api/v1/` is\n *      `listV1` and `listV1No2`, never `listV12`, which reads as version\n *      12. An operationId-named operation keeps the plain name over a\n *      path-named one; then the path\n *      that skipped the shorter root, so `/health` or a tagged `/notes` keeps\n *      `list` over `/api/health` or `/api/v1/notes`; otherwise the lexically\n *      first path keeps it, whatever the document order. The suffix is silent\n *      for a path-derived name, like a hashed inline model name; it comes\n *      with a warning when the document reuses an operationId, since that\n *      changes a name the author chose.\n *\n * Each qualifier depends only on the paths in the group, never on their\n * document order, and each runs once, so the result is deterministic.\n */\nfunction disambiguateOperationNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  serviceName: string,\n  apiRootLengthOf: (op: Operation) => number,\n): void {\n  const rename = (op: Operation, name: string) => {\n    (op as { name: string }).name = name;\n  };\n  // The noun an operation's path names: its resource, or, for the service's\n  // own path, the service noun the plain name left off (`Notes` for `/notes`\n  // and for `/notes/{noteId}/notes` alike, `Note` for their items). What\n  // nameIsFree compares when another path-named operation holds a proposal.\n  const nounOf = (op: Operation): string | null => {\n    const root = apiRootLengthOf(op);\n    return inferResourceFromPath(op.path, root) ?? inferServiceNoun(op.path, root);\n  };\n  /** The names every operation of the service outside `group` has right now, operationIds included. */\n  const namesOutside = (group: Operation[]): ReadonlySet<string> => {\n    const members = new Set(group);\n    return new Set(operations.filter((op) => !members.has(op)).map((op) => op.name));\n  };\n  /** One pass on one group, through the rule every pass shares (qualifyGroup). */\n  const qualify = (group: Operation[], proposal: (op: Operation) => string) =>\n    qualifyGroup(group, operations, pathNamed, nounOf, proposal, rename);\n\n  // One path first: the qualifiers below tell paths apart and leave a name\n  // shared on one path alone, so that sharing is settled before they run.\n  const demoted = demoteSamePathNames(operations, pathNamed, serviceName, apiRootLengthOf, rename);\n  // Then an action beside a CRUD or singleton operation of its name: the\n  // plain name stays with the latter, which the qualifiers would rename.\n  for (const op of yieldActionNames(operations, pathNamed, demoted, apiRootLengthOf, rename)) demoted.add(op);\n\n  // Each qualifier, given the group, is the word or words a path-named\n  // member would add to its name: `null` or `''` when its path has none.\n  const qualifiers: Array<(group: Operation[]) => (op: Operation) => string | null> = [\n    (group) => (op) => {\n      const root = apiRootLengthOf(op);\n      const resource = inferResourceFromPath(qualifierPath(op, root, !demoted.has(op)), root);\n      if (resource !== null) return resource;\n      // The service's own path left its noun off the plain name (`list` for\n      // `/notes`). It is proposed here, ahead of the service-noun pass, when a\n      // path-named operation outside the group already carries it under the\n      // name it would make — the nested collection of the same word,\n      // `/notes/{noteId}/notes` as `listNotes` — so the two take one spelling\n      // (nameIsFree) and the parameters tell them apart, `listNotes` and\n      // `listNotesByNoteId`, rather than the nested collection keeping the\n      // name the service's own path restores beside an operationId.\n      const noun = inferServiceNoun(op.path, root);\n      if (noun === null) return null;\n      const name = appendQualifier(op.name, noun);\n      const held = operations.some((other) => !group.includes(other) && pathNamed.has(other) && other.name === name);\n      return held && nameIsFree(group, operations, pathNamed, nounOf, op, name) ? noun : null;\n    },\n    (group) => {\n      // Singular, like the resource of an item operation, unless that\n      // spelling gives a path the name of an operation outside the group or\n      // of another path in the group whose spelling as written differs: the\n      // plural is then what tells them apart, so the path takes its context\n      // as written. `/store/pets/{id}/toys/{toyId}` beside\n      // `/store/pet/{id}/toys/{toyId}` is `getToyPets` and `getToyPet`, and\n      // `/store/cats/{id}/toys/{toyId}` beside `operationId: getToyCat` is\n      // `getToyCats`. As written, too, when another path in the group\n      // writes the same words but singularises them differently — `teams`\n      // in `/org/teams/members` and in `/org/teams/{teamId}/members` — so\n      // one spelling in the paths is one spelling in the names, `Teams` for\n      // both, which tells nothing apart (qualifyGroup) and leaves the\n      // parameters to do it: `listMembers` and `listMembersByTeamId`, never\n      // `listMembersTeams` beside `listMembersTeam` (issue #288). Two paths\n      // whose contexts agree in both spellings (`/orgs/teams/{id}/members`\n      // and `/orgs/{orgId}/teams/{id}/members`) stay singular and go on to\n      // the parameters together. Both spellings are read before any member\n      // is renamed, so the outcome does not depend on document order.\n      const outside = namesOutside(group);\n      const spelled = new Map(\n        group\n          .filter((op) => pathNamed.has(op))\n          .map((op) => {\n            const root = apiRootLengthOf(op);\n            const path = qualifierPath(op, root, !demoted.has(op));\n            return [\n              op,\n              {\n                singular: inferDeeperContext(path, root),\n                written: inferDeeperContext(path, root, false),\n                singularName: appendQualifier(op.name, inferDeeperContext(path, root)),\n                writtenName: appendQualifier(op.name, inferDeeperContext(path, root, false)),\n              },\n            ] as const;\n          }),\n      );\n      return (op) => {\n        const own = spelled.get(op);\n        if (own === undefined) return null;\n        const asWritten =\n          own.writtenName !== own.singularName &&\n          (outside.has(own.singularName) ||\n            [...spelled].some(\n              ([other, spelling]) =>\n                other.path !== op.path &&\n                (spelling.singularName === own.singularName) !== (spelling.writtenName === own.writtenName),\n            ));\n        return asWritten ? own.written : own.singular;\n      };\n    },\n    (group) => {\n      // Parameters only help when they differ between the colliding paths,\n      // so one every path carries is left out — `/api/notes/{noteId}` and\n      // `/api/{teamId}/notes/{noteId}` are told apart by `teamId` alone —\n      // and when none does, every proposal reads alike and qualifyGroup\n      // skips the pass: `/v1/{id}/notes` and `/v1/{id}/Notes` would both\n      // gain `ById` and still collide, further from the plain name. Every\n      // path-named operation takes part, under an API root or not: a service\n      // must not hand an emitter two methods with one name.\n      const shared = sharedPathParams(group.map((op) => op.path));\n      return (op) => inferByParamsSuffix(op.path, shared);\n    },\n    (group) => {\n      // Paths under the document root that skipped different lengths of it\n      // differ by a version or mount word the plain name left off: `/api/notes`\n      // beside `/api/v1/notes` in `Notes`. The words a path skipped beyond the\n      // root the rooted paths all share are what tell them apart (`listV1`),\n      // the one place a root word belongs in a name. A root-less path — outside\n      // the root, or tagged — is named as if the document had none and takes\n      // no part; it keeps the plain name in the numeric pass instead.\n      const rooted = group.map((op) => pathSegments(op.path).slice(0, apiRootLengthOf(op))).filter((r) => r.length > 0);\n      let shared = rooted[0] ?? [];\n      for (const root of rooted) shared = shared.slice(0, sharedPrefixLength(shared, root));\n      return (op) => toPascalCase(pathSegments(op.path).slice(shared.length, apiRootLengthOf(op)).join('_'));\n    },\n    () => (op) => {\n      // The plain name leaves off the resource noun that names the service\n      // (`GET /api/notes` in `Notes` is `list`); it is restored when it is\n      // what tells the group apart. An operationId-named operation is never\n      // renamed, so it contributes nothing here: next to `operationId: list`\n      // on `/api/{teamId}/notes`, path-named `/api/notes` becomes\n      // `listNotes`. When every path drops the same noun (`/notes` and\n      // `/api/v1/notes`), restoring it would only move the collision, and\n      // qualifyGroup skips the pass.\n      return inferServiceNoun(op.path, apiRootLengthOf(op));\n    },\n  ];\n\n  for (const qualifier of qualifiers) {\n    for (const group of collidingGroups(operations)) {\n      const words = qualifier(group);\n      qualify(group, (op) => appendQualifier(op.name, words(op)));\n    }\n  }\n\n  // The plural a member could take back: none for an operationId-named\n  // operation, and for a path-named one only while its name is still the one\n  // it was built with — no qualifier above has extended it. Like every pass,\n  // only when it tells the group apart: beside an operationId, which has no\n  // plural, or beside a path that spells the resource singular\n  // (`/store/pet/{id}`). The plural is compared as written, since its number\n  // is the whole point; members that would all take the same plural are left\n  // to the numeric suffix.\n  const pluralOf = (op: Operation): string | null => {\n    const root = apiRootLengthOf(op);\n    const actions = !demoted.has(op);\n    if (op.name !== fallbackOperationName(op.httpMethod, op.path, root, actions)) return null;\n    return pluralFallbackName(op.httpMethod, op.path, root, actions);\n  };\n  for (const group of collidingGroups(operations)) {\n    // Like every qualifier, only when it tells the group apart: beside an\n    // operationId, which has no plural, or beside a path that spells the\n    // resource singular (`/store/pet/{id}`). Members that would all take the\n    // same plural are left to the numeric suffix. A plural is blocked only by\n    // a name outside the group (`operationId: getPets`); members that share\n    // one some other member does not (`/store/Pets/{id}` and\n    // `/store/pets/{id}` beside `/store/pet/{id}`) take it together and are\n    // numbered below, `getPets` and `getPets2` — the names such a document\n    // produced before item resources were singularised. Two groups never\n    // share a plural: it is the group's singular name with the resource as\n    // written, so one plural means one singular name, and one group.\n    qualify(group, (op) => pluralOf(op) ?? op.name);\n  }\n\n  const taken = new Set(operations.map((op) => op.name));\n  for (const group of collidingGroups(operations)) {\n    const name = group[0].name;\n    // An operationId-named operation outranks a path-named one for the plain\n    // name; then the path that skipped the shorter API root, so a root-less\n    // path (`/health`, or a tagged `/notes`) keeps the name it has always had\n    // over `/api/health` or `/api/v1/notes`; within that the lexically first\n    // path wins. The outcome never depends on document order, and operations\n    // on one path share it.\n    const rank = (op: Operation) => (pathNamed.has(op) ? 1 : 0);\n    const ordered = [...group].sort(\n      (a, b) => rank(a) - rank(b) || apiRootLengthOf(a) - apiRootLengthOf(b) || comparePaths(a, b),\n    );\n    const keeper = ordered[0];\n    const nameByPath = new Map<string, string>([[keeper.path, name]]);\n    for (const op of ordered) {\n      let next = nameByPath.get(op.path);\n      if (next === undefined) {\n        next = suffixedName(name, taken);\n        taken.add(next);\n        nameByPath.set(op.path, next);\n        // A path-derived name is the parser's own and is refined silently,\n        // like a hashed inline model name. A name the document chose is only\n        // changed when the document reuses it, which is worth saying.\n        if (!pathNamed.has(op)) {\n          console.warn(\n            `[oagen] Warning: Operations ${keeper.httpMethod.toUpperCase()} ${keeper.path} and ` +\n              `${op.httpMethod.toUpperCase()} ${op.path} in service ${serviceName} both take the name ` +\n              `\"${name}\" from their operationId; the latter is renamed \"${next}\" — give each a distinct operationId`,\n          );\n        }\n      }\n      rename(op, next);\n    }\n  }\n\n  // Once more on one path, after every pass: a rename above can land on a\n  // name an operation on the same path holds (see numberSamePathNames).\n  numberSamePathNames(operations, pathNamed, rename);\n}\n\n/**\n * Give operations on one path distinct names when their methods take\n * different CRUD verbs. Two operations on one path share a name only when\n * both are path-named and their methods take the same verb (inferVerb): PUT\n * and PATCH are both `update`, so `/pets/{id}` has one `updatePet` for the\n * two, as it always has. Any other sharing hides one of the two from every\n * consumer that keys a service's operations by name, such as the differ, and\n * an action name is where it arises: `bulk-delete` is the action of a DELETE\n * (its own verb) and of a POST (a CRUD verb last), so both would be\n * `bulkDelete`.\n *\n * The name stays with one verb, and every path-named operation of another\n * verb takes the name it has without the action rule (fallbackOperationName\n * with `actions` false): `POST /pets/bulk-delete` beside a DELETE is\n * `createBulkDelete`, and `POST /users/{id}/update-password` beside a PUT is\n * the singleton `createUserUpdatePassword`. The verb that keeps the name: an\n * operationId-named operation's, since that name is the author's and a\n * path-named sibling steps aside whatever its verb; else the verb the segment\n * carries (segmentCarriesVerb), `delete` for `bulk-delete`, the first\n * method's in HTTP_METHODS order when it carries two; else `create`, POST\n * being the only other method an action is read on (inferAction); else, for\n * a shared name that is no action (PUT and PATCH `updatePet`), the verb of\n * the first method in HTTP_METHODS order. When the name an operation falls back to is\n * still held on the path by an operationId or by another verb — path-named\n * PATCH `updatePet` beside `operationId: updatePet` on the PUT has no action\n * to drop — a numeric suffix free in the service is added, silently, as the\n * numeric pass adds one and spelled as it spells it (numberedName:\n * `updatePet2`, and `updateTop10No2` for a PATCH on `/store/top10/{id}`\n * beside `operationId: updateTop10`). Two operationId-named operations on\n * one path with one name are the document reusing an operationId: the first\n * in HTTP_METHODS order keeps it and the rest are numbered with the warning\n * the numeric pass gives that case. Paths are visited in lexical order and\n * their operations in HTTP_METHODS order, so the result depends only on the\n * document's paths and methods.\n *\n * Returns the path-named operations that gave an action name up, whose\n * qualifiers and plural read their path as the shape they fell back to.\n */\nfunction demoteSamePathNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  serviceName: string,\n  apiRootLengthOf: (op: Operation) => number,\n  rename: (op: Operation, name: string) => void,\n): Set<Operation> {\n  const demoted = new Set<Operation>();\n  const taken = new Set(operations.map((op) => op.name));\n  const verbOf = (op: Operation) => inferVerb(op.httpMethod, op.path);\n  // The verb that keeps a shared action name among path-named operations.\n  const claim = (op: Operation) => (segmentCarriesVerb(op.httpMethod, op.path) ? 0 : op.httpMethod === 'post' ? 1 : 2);\n\n  for (const onPath of operationsByPath(operations).values()) {\n    const byName = new Map<string, Operation[]>();\n    for (const op of onPath) byName.set(op.name, [...(byName.get(op.name) ?? []), op]);\n    for (const [name, sharing] of byName) {\n      if (sharing.length < 2) continue;\n      const explicit = sharing.filter((op) => !pathNamed.has(op));\n      for (const op of explicit.slice(1)) {\n        const next = suffixedName(name, taken);\n        console.warn(\n          `[oagen] Warning: Operations ${explicit[0].httpMethod.toUpperCase()} ${explicit[0].path} and ` +\n            `${op.httpMethod.toUpperCase()} ${op.path} in service ${serviceName} both take the name ` +\n            `\"${name}\" from their operationId; the latter is renamed \"${next}\" — give each a distinct operationId`,\n        );\n        rename(op, next);\n        taken.add(next);\n      }\n      const keeper =\n        explicit.length > 0 ? null : [...sharing].sort((a, b) => claim(a) - claim(b) || methodOrder(a, b))[0];\n      const keptVerb = keeper === null ? null : verbOf(keeper);\n      for (const op of sharing) {\n        if (!pathNamed.has(op) || verbOf(op) === keptVerb) continue;\n        const base = fallbackOperationName(op.httpMethod, op.path, apiRootLengthOf(op), false);\n        // Still held on the path by an operationId or another verb? Number it.\n        const held = onPath.some(\n          (other) => other !== op && other.name === base && (!pathNamed.has(other) || verbOf(other) !== verbOf(op)),\n        );\n        const next = held ? suffixedName(base, taken) : base;\n        if (next !== op.name) {\n          rename(op, next);\n          taken.add(next);\n        }\n        demoted.add(op);\n      }\n    }\n  }\n  return demoted;\n}\n\n/**\n * Keep the plain CRUD name with the CRUD operation when an action takes it.\n * `POST /pets/update` is the action `update` — its collection `pets` is the\n * service segment, which a name leaves off — and so is `PUT /pets/{id}`. Left\n * to the qualifiers, the pair would be told apart by `By<Param>`, which\n * renames the PUT to `updateById`, and code calling `update` would then\n * reach `POST /pets/update`. So before the qualifiers run, a path-named\n * action that shares its name with a path-named operation of another shape —\n * a CRUD operation or a singleton, for which inferAction is null, a demoted\n * action among them — is renamed alone. It takes back the collection it\n * dropped, the service noun of the path the action segment sits on\n * (inferServiceNoun of qualifierPath): `updatePets`, `createPets` for\n * `POST /pets/create` beside `POST /pets`, `listAllPets` for\n * `GET /pets/list-all` beside `GET /pets/all`. When that adds nothing —\n * the name already ends with it (`POST /store/pets/{id}/create` is\n * `createPet`, as `POST /store/pets/{id}` is) or there is none\n * (`POST /store/pets/update` is `updatePets`, as `PUT /store/pets` is) — it\n * takes the name it has without the action rule (`createPetCreate`,\n * `createUpdate`) and is read from then on\n * as that shape, like a demoted action (demoteSamePathNames). An action\n * beside an operationId of its name is left to the numeric pass\n * (`adoptPet2`), and two actions of one name to the qualifiers\n * (`adoptPetRescue`). Groups come in name order and the renames depend only\n * on each operation's own path, so the result is deterministic. Returns the\n * operations that fell back to their non-action name.\n */\nfunction yieldActionNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  demoted: ReadonlySet<Operation>,\n  apiRootLengthOf: (op: Operation) => number,\n  rename: (op: Operation, name: string) => void,\n): Operation[] {\n  const fellBack: Operation[] = [];\n  const isAction = (op: Operation) =>\n    pathNamed.has(op) && !demoted.has(op) && inferAction(op.httpMethod, op.path, apiRootLengthOf(op)) !== null;\n  // Every name the service holds, kept current as actions are renamed, so a\n  // rename never lands on a name another operation already has — least of\n  // all one on the action's own path, which no later pass looks at again.\n  const taken = new Set(operations.map((op) => op.name));\n  for (const group of collidingGroups(operations)) {\n    if (!group.some((op) => pathNamed.has(op) && !isAction(op))) continue;\n    for (const op of group.filter(isAction)) {\n      const root = apiRootLengthOf(op);\n      const qualified = appendQualifier(op.name, inferServiceNoun(qualifierPath(op, root), root));\n      const plain = fallbackOperationName(op.httpMethod, op.path, root, false);\n      const next =\n        [qualified, plain].find((name) => name !== op.name && !taken.has(name)) ?? suffixedName(plain, taken);\n      rename(op, next);\n      taken.add(next);\n      if (next !== qualified) fellBack.push(op);\n    }\n  }\n  return fellBack;\n}\n\n/**\n * The last check on one path, after every pass has run. Each pass renames\n * path-named operations, and a new name can be one another operation on the\n * same path already holds: the service noun restored to `GET /api/notes`\n * beside `operationId: list` on `/api/{teamId}/notes` is `listNotes`, which\n * `POST /api/notes` may carry as its operationId. No pass after the first\n * looks at one path again, since collidingGroups leaves a name shared on one\n * path alone, so the sharing rule of demoteSamePathNames is applied once\n * more here: a path-named operation that shares its name with an\n * operationId-named operation on its path, or with a path-named one of\n * another CRUD verb, takes the first numeric suffix free in the service,\n * silently, as the numeric pass numbers a path-named operation. The keeper is\n * the operationId-named operation, else the first path-named one in\n * HTTP_METHODS order.\n */\nfunction numberSamePathNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  rename: (op: Operation, name: string) => void,\n): void {\n  const taken = new Set(operations.map((op) => op.name));\n  const verbOf = (op: Operation) => inferVerb(op.httpMethod, op.path);\n  for (const onPath of operationsByPath(operations).values()) {\n    const byName = new Map<string, Operation[]>();\n    for (const op of onPath) byName.set(op.name, [...(byName.get(op.name) ?? []), op]);\n    for (const [name, sharing] of byName) {\n      if (sharing.length < 2) continue;\n      const keeper = sharing.find((op) => !pathNamed.has(op)) ?? sharing[0];\n      for (const op of sharing) {\n        if (op === keeper || !pathNamed.has(op)) continue;\n        if (pathNamed.has(keeper) && verbOf(op) === verbOf(keeper)) continue;\n        const next = suffixedName(name, taken);\n        rename(op, next);\n        taken.add(next);\n      }\n    }\n  }\n}\n\n/**\n * The operations of a service grouped by path, paths in lexical order and\n * each path's operations in HTTP_METHODS order, so a pass over them depends\n * only on the document's paths and methods, never on its order.\n */\nfunction operationsByPath(operations: Operation[]): Map<string, Operation[]> {\n  const byPath = new Map<string, Operation[]>();\n  for (const op of operations) byPath.set(op.path, [...(byPath.get(op.path) ?? []), op]);\n  return new Map([...byPath.keys()].sort().map((path) => [path, (byPath.get(path) ?? []).sort(methodOrder)]));\n}\n\n/** Operations in HTTP_METHODS order (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE). */\nfunction methodOrder(a: Operation, b: Operation): number {\n  return HTTP_METHODS.indexOf(a.httpMethod) - HTTP_METHODS.indexOf(b.httpMethod);\n}\n\n/**\n * `base` with the first numeric suffix, from 2, that no name in `taken` has,\n * spelled by numberedName: `updatePet2`, and `updateTop10No2` for a base\n * that ends in a digit.\n */\nfunction suffixedName(base: string, taken: ReadonlySet<string>): string {\n  let n = 2;\n  while (taken.has(numberedName(base, n))) n++;\n  return numberedName(base, n);\n}\n\n/**\n * The groups of operations that share a name but not a path, in name order.\n * A name shared only by operations on one path is not a collision and is\n * excluded: after demoteSamePathNames such operations are path-named and\n * their methods take one verb (PUT + PATCH).\n *\n * Name order, not document order: the numeric pass draws suffixed names from\n * one pool per service, and two groups can reach the same one (`listNotes1`\n * + `No2` and `listNotes1No` + `2`, see numberedName), so whichever is\n * served first decides. Names are unique per group, so this is a total\n * order, and with the members of a group also sorted the whole assignment\n * depends only on the paths.\n */\nfunction collidingGroups(operations: Operation[]): Operation[][] {\n  const byName = new Map<string, Operation[]>();\n  for (const op of operations) {\n    const group = byName.get(op.name) ?? [];\n    group.push(op);\n    byName.set(op.name, group);\n  }\n  return [...byName.entries()]\n    .filter(([, group]) => new Set(group.map((op) => op.path)).size > 1)\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([, group]) => group);\n}\n\n/** Operations in path order, by code unit, the one tie-break every pass of disambiguateOperationNames uses. */\nfunction comparePaths(a: Operation, b: Operation): number {\n  return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;\n}\n\n/**\n * One pass of disambiguateOperationNames on one colliding group: the group's\n * path-named members take the names the pass proposes for them when the pass\n * tells the group apart, and only names no operation outside the group has.\n * An operationId-named member is never renamed and stands at its own name.\n *\n * `proposal` is the name a path-named member would take, compared as\n * written: a pass that must not part two paths on a word's number alone\n * spells it alike for both before proposing (the deeper context of\n * `/org/teams/members` and `/org/teams/{teamId}/members` is `Teams` for\n * both, never `Teams` beside `Team`), and a pass whose number is the point\n * (the plural, `getPets` beside `getPet`) proposes it as it is. Three rules\n * follow, each on this one place:\n *\n *   - The pass is skipped for the group when every proposal is one name. A\n *     qualifier the colliding paths all carry — `Teams` above — would move\n *     the collision further from the plain name and tell nothing apart; the\n *     next pass (`ByTeamId`) is what does.\n *   - A proposal an operation outside the group already has is not taken\n *     (nameIsFree): the member keeps its name for this pass and the next pass\n *     is tried, so `/org/members/archived` beside `/org/archived_members`,\n *     whose name is `listArchivedMembers`, is never `listArchivedMembers2`,\n *     which reads as a variant of a path it is unrelated to; a number is for\n *     when no pass is left. Its colliding twin `/org/teams/archived` still\n *     takes `listArchivedTeams`, and `listArchived` is then its own.\n *   - Members with one proposal stay one group for the next pass: they take\n *     it together — `/orgs/{orgId}/groups/members` and\n *     `/orgs/{orgId}/groups/{groupId}/members` beside `/orgs/teams/members`\n *     are `listMembersGroups` both, told apart next by `ByGroupId` — and are\n *     numbered on it when nothing after tells them apart. Members on one path\n *     (PUT + PATCH) share a name by the same rule.\n *\n * Which names are taken is read when the group is reached, so groups a pass\n * served earlier — in name order (collidingGroups) — hold their new names\n * against it, and the outcome depends only on the paths.\n */\nfunction qualifyGroup(\n  group: readonly Operation[],\n  operations: readonly Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  nounOf: (op: Operation) => string | null,\n  proposal: (op: Operation) => string,\n  rename: (op: Operation, name: string) => void,\n): void {\n  const proposals = new Map(group.map((op) => [op, pathNamed.has(op) ? proposal(op) : op.name]));\n  const clusters = new Map<string, Operation[]>();\n  for (const op of [...group].sort(comparePaths)) {\n    const name = proposals.get(op) ?? op.name;\n    clusters.set(name, [...(clusters.get(name) ?? []), op]);\n  }\n  if (clusters.size <= 1) return;\n  for (const [name, members] of clusters) {\n    if (!members.every((op) => nameIsFree(group, operations, pathNamed, nounOf, op, name))) continue;\n    for (const op of members) {\n      if (pathNamed.has(op)) rename(op, name);\n    }\n  }\n}\n\n/**\n * Whether `name` is free for `op`, a member of `group`: no operation outside\n * the group has it, or every operation that has it is path-named and names\n * the noun `op` names (`nounOf`, compared as sameNoun compares) — the nested\n * collection of the service's own word, `/notes/{noteId}/notes` as\n * `listNotes` beside `/notes`. Such a name the member takes and joins the\n * group of, and the passes after tell the two apart by what does differ\n * between their paths: `listNotes` and `listNotesByNoteId`, `getNote` and\n * `getNoteByChildId`. A name an operationId-named operation has is never\n * free, nor is one a path-named operation of another noun has:\n * `listArchivedMembers` on `/org/archived_members` beside the `Archived` of\n * `/org/members/archived`, which nothing after could tell apart.\n */\nfunction nameIsFree(\n  group: readonly Operation[],\n  operations: readonly Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  nounOf: (op: Operation) => string | null,\n  op: Operation,\n  name: string,\n): boolean {\n  const noun = nounOf(op);\n  return operations.every((other) => {\n    if (group.includes(other) || other.name !== name) return true;\n    const otherNoun = pathNamed.has(other) ? nounOf(other) : null;\n    return noun !== null && otherNoun !== null && sameNoun(otherNoun.toLowerCase(), noun.toLowerCase());\n  });\n}\n\n/**\n * `name` with the numeric suffix `n`, the spelling of every numbered\n * operation name (suffixedName picks the first free `n`): `list` + 2 is\n * `list2`. A name that already ends in a digit takes the number behind\n * `No`, so that it cannot be read as part of the number the name ends with:\n * `listV1` + 2 is `listV1No2`, never `listV12`, which reads as version 12\n * of the API, and `listTop10` + 2 is `listTop10No2`. An underscore would\n * not do: splitWords reads a digit run as a word of its own, so `listV1_2`\n * re-cased by toPascalCase or toCamelCase is `ListV12` or `listV12` again.\n */\nfunction numberedName(name: string, n: number): string {\n  return /\\d$/.test(name) ? `${name}No${n}` : `${name}${n}`;\n}\n\n/**\n * Append a qualifier to an operation name without repeating what the name\n * already says. A qualifier never contributes the same word twice in a row:\n * the deeper context of `/api/analytics/analytics/teams` is\n * `AnalyticsAnalytics`, which joins as `listTeamsAnalytics`. The words that\n * remain are then joined where they overlap the end of the name: `listNotes`\n * + `Notes` and `listOAuth2Tokens` + `OAuth2Tokens` stay as they are, and\n * `listTeams` + `TeamsAnalytics` is `listTeamsAnalytics`. Words are compared\n * on the camelCase boundary, case-insensitively and as nouns (sameNoun), so\n * a noun the name ends with is not repeated in the other number either:\n * `listNotes` + `Note` and `listAliases` + `Alias`, the deeper contexts of\n * `/orgs/notes/{id}/notes` and `/org/aliases/{id}/aliases`, stay `listNotes`\n * and `listAliases`. The name's own words are never touched.\n */\nfunction appendQualifier(name: string, qualifier: string | null): string {\n  if (!qualifier) return name;\n  const have = splitWords(name).map((w) => w.toLowerCase());\n  const words = splitWords(qualifier).filter(\n    (w, i, all) => i === 0 || !sameNoun(w.toLowerCase(), all[i - 1].toLowerCase()),\n  );\n  const want = words.map((w) => w.toLowerCase());\n  // The longest run of words that both ends the name and starts the qualifier.\n  let overlap = Math.min(have.length, want.length);\n  while (overlap > 0 && !want.slice(0, overlap).every((w, i) => sameNoun(w, have[have.length - overlap + i]))) {\n    overlap--;\n  }\n  const rest = words.slice(overlap);\n  return rest.length === 0 ? name : toCamelCase([name, ...rest].join('_'));\n}\n\n/**\n * Whether two lowercase words name one noun: they are the same word, or\n * their singular forms (singularizePathSegment) are — `notes` and `note`,\n * `aliases` and `alias`, `analyses` and `analysis`. singularizePathSegment\n * is idempotent, so a word that is already singular is its own singular\n * form and is never shortened a second time on one side only (`alias`\n * compares as `alias`, not `alia`, against the `alias` that `aliases`\n * becomes). Two words the stemmer cannot relate, `canvases` and `canvas`,\n * are different nouns here, as they are everywhere else.\n */\nfunction sameNoun(a: string, b: string): boolean {\n  return a === b || singularizePathSegment(a) === singularizePathSegment(b);\n}\n\n/**\n * The path a colliding operation's resource and deeper context are read\n * from: the path without the segments whose words the name already carries\n * ahead of its last word, so that what remains ends with the word the name\n * ends with, which appendQualifier leaves alone, and the rest is what sets\n * the colliding paths apart.\n *\n * For an action (inferAction) it is the path without the action segment:\n * `adoptPet` on `/shop/rescue/pets/{id}/adopt` is read as\n * `/shop/rescue/pets/{id}`, whose resource `Pet` the name ends with and whose\n * deeper context `Rescue` tells it from `/shop/pets/{id}/adopt`, rather than\n * the verb coming back as `adoptPetAdopt`. For a singleton (inferSingleton)\n * it is the path without the parent (itemParentIndex) and the parameter\n * before the segment: `getPetStatus` on `/shop/rescue/pets/{id}/status` is\n * read as `/shop/rescue/status`, whose resource `Status` the name ends with,\n * so the same `Rescue` tells it from `/shop/pets/{id}/status` rather than\n * `Pet` coming back as `getPetStatusPet`. Every other operation is read\n * whole, as is an action that gave its name up on its path\n * (demoteSamePathNames; `actions` false), whose name is the next shape's.\n */\nfunction qualifierPath(op: Operation, apiRootLength: number, actions = true): string {\n  const segments = pathSegments(op.path);\n  if (actions && inferAction(op.httpMethod, op.path, apiRootLength)) return '/' + segments.slice(0, -1).join('/');\n  if (inferSingleton(op.path, apiRootLength)) {\n    const parent = itemParentIndex(segments, apiRootLength);\n    return '/' + segments.filter((_, i) => i !== parent && i !== segments.length - 2).join('/');\n  }\n  return op.path;\n}\n\n/**\n * The path parameters in path order, each as the PascalCase word that\n * `By<Param>` spells it with. Mirrors derivePathModelBaseName's spelling of a\n * parameter segment, so `{team_id}` and `{teamId}` read alike. A parameter\n * that carries a custom method (`{petId}:adopt`) is the parameter alone,\n * `PetId`, since pathSegments has split the verb off.\n */\nfunction pathParamWords(path: string): string[] {\n  return pathSegments(path)\n    .filter((segment) => segment.startsWith('{'))\n    .map((segment) => toPascalCase(segment.replace(/[{}]/g, '')));\n}\n\n/** The parameter words (pathParamWords) that every one of the paths carries. */\nfunction sharedPathParams(paths: readonly string[]): ReadonlySet<string> {\n  const words = paths.map((path) => new Set(pathParamWords(path)));\n  return new Set([...(words[0] ?? [])].filter((word) => words.every((set) => set.has(word))));\n}\n\n/**\n * `By<Param>` for each path parameter not in `shared`, in path order, as one\n * qualifier: `/v1/{teamId}/notes` → `ByTeamId`, `/a/{x}/b/{y}/c` → `ByXByY`,\n * and `/api/{teamId}/notes/{noteId}` → `ByTeamId` when the colliding paths\n * all carry `noteId`. Empty for a path with no parameter of its own.\n */\nfunction inferByParamsSuffix(path: string, shared: ReadonlySet<string>): string {\n  return pathParamWords(path)\n    .filter((word) => !shared.has(word))\n    .map((word) => 'By' + word)\n    .join('');\n}\n\n/**\n * The resource noun inferResourceFromPath leaves off because it is the\n * segment the service was named from, spelled as that function would have\n * spelled it (pathSegmentNoun): `Notes` for `/api/notes` and\n * `/api/{teamId}/notes` under an `/api` root and for a root-less `/notes`,\n * `Note` for the item `/api/notes/{id}`. Null when the last literal segment\n * past the API root is a different word (`/api/notes/{id}/tags`, whose `Tags`\n * the plain name already carries) or when nothing literal follows the root\n * (`/api/v1/{id}`).\n */\nfunction inferServiceNoun(path: string, apiRootLength: number): string | null {\n  const segments = pathSegments(path);\n  let last = segments.length - 1;\n  while (last >= apiRootLength && segments[last].startsWith('{')) last--;\n  if (last < apiRootLength || last !== serviceSegmentIndex(path, apiRootLength)) return null;\n  return toPascalCase(pathSegmentNoun(segments, last));\n}\n\n/**\n * Extract a deeper disambiguation context from the path when the resource\n * noun isn't unique enough: the literal segments between the service segment\n * and the resource, joined in path order, each spelled as pathSegmentNoun\n * spells it — singular when a path parameter follows it, since the segment\n * then addresses one item, and as written otherwise.\n *\n * /users/{id}/legacy/factors → \"Legacy\"\n * /store/cats/{id}/toys/{toyId} → \"Cat\" (one cat's toys), so `getToyCat` beside `/store/dogs/{id}/toys/{toyId}`\n * /store/cats/toys/{toyId} → \"Cats\" (no one cat), so `getToyCats` beside `/store/dogs/toys/{toyId}`\n * /org/analytics/analytics/teams → \"AnalyticsAnalytics\" (appendQualifier collapses the repeat)\n * /users/{id}/auth_factors → null: nothing lies between the service and the resource\n *\n * `Cat` and `Cats` are one noun, so beside each other the two cat paths are\n * not told apart by it (qualifyGroup): `/store/cats/{id}/toys/{toyId}` and\n * `/store/cats/toys/{toyId}` are `getToyById` and `getToy`, by the\n * parameter that does tell them apart.\n *\n * The API root the path sits under (`apiRootLength`, see documentApiRoot) is\n * left out along with the service segment that follows it, so\n * /api/v1/core/auth/permissions in `Core` contributes \"Auth\", not \"V1CoreAuth\".\n * `singularItem` false keeps every segment as the path spells it (`Pets` for\n * `/store/pets/{id}/toys/{toyId}`), for the qualifier that falls back to the\n * plural when the singular does not tell two paths apart (see\n * disambiguateOperationNames). The stemmer's limits reach every segment it\n * singularises: `/messages/sms/{smsId}/attachments` contributes \"Sm\".\n */\nfunction inferDeeperContext(path: string, apiRootLength = 0, singularItem = true): string | null {\n  const segments = pathSegments(path);\n  const nouns: string[] = [];\n  for (let i = apiRootLength; i < segments.length; i++) {\n    if (!segments[i].startsWith('{')) nouns.push(singularItem ? pathSegmentNoun(segments, i) : segments[i]);\n  }\n  // Skip first (service) and last (already used) — use the middle ones\n  if (nouns.length >= 3) {\n    return toPascalCase(nouns.slice(1, -1).join('_'));\n  }\n  return null;\n}\n\n/**\n * Extract mutually-exclusive parameter groups from the `x-mutually-exclusive-parameter-groups`\n * operation extension. Cross-references grouped parameter names against the already-extracted\n * IR parameter arrays so emitters get object-identity references.\n */\nfunction extractParameterGroups(\n  op: OperationObject,\n  allIRParams: Parameter[],\n  operationContext: string,\n): ParameterGroup[] | undefined {\n  const raw = op['x-mutually-exclusive-parameter-groups'];\n  if (!raw || typeof raw !== 'object') return undefined;\n\n  const paramByName = new Map<string, Parameter>();\n  for (const p of allIRParams) {\n    paramByName.set(p.name, p);\n  }\n\n  const groups: ParameterGroup[] = [];\n\n  for (const [groupName, groupDef] of Object.entries(raw)) {\n    if (!groupDef || typeof groupDef !== 'object') {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName} in ${operationContext}: expected an object with \"optional\" and \"variants\".`,\n      );\n    }\n\n    if (typeof groupDef.optional !== 'boolean') {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName}.optional in ${operationContext}: expected a boolean.`,\n      );\n    }\n\n    if (!groupDef.variants || typeof groupDef.variants !== 'object') {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName}.variants in ${operationContext}: expected an object mapping variant names to parameter name arrays.`,\n      );\n    }\n\n    if (Object.keys(groupDef.variants).length === 0) {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName} in ${operationContext}: group has zero variants.`,\n      );\n    }\n\n    const variants = Object.entries(groupDef.variants).map(([variantName, paramNames]) => {\n      if (!Array.isArray(paramNames) || paramNames.length === 0) {\n        throw new Error(\n          `Malformed x-mutually-exclusive-parameter-groups.${groupName}.variants.${variantName} in ${operationContext}: expected a non-empty array of parameter names.`,\n        );\n      }\n      const parameters: Parameter[] = paramNames.map((pName) => {\n        const irParam = paramByName.get(pName);\n        if (!irParam) {\n          throw new Error(\n            `x-mutually-exclusive-parameter-groups.${groupName}.variants.${variantName} references parameter \"${pName}\" which does not exist in the operation's parameters[] (${operationContext}).`,\n          );\n        }\n        return irParam;\n      });\n      return { name: variantName, parameters };\n    });\n\n    groups.push({\n      name: groupName,\n      optional: groupDef.optional,\n      variants,\n    });\n  }\n\n  return groups.length > 0 ? groups : undefined;\n}\n\n/**\n * Extract mutually-exclusive body parameter groups from the\n * `x-mutually-exclusive-body-groups` operation extension. Unlike query\n * parameter groups (whose parameters live in operation.queryParams), body\n * group parameters are synthetic — built from the oneOf variant schemas in\n * the request body. Emitters use the group's presence to generate sum-type\n * interfaces and custom JSON marshalling instead of flat optional fields.\n */\nfunction extractBodyParameterGroups(\n  op: OperationObject,\n  requestBody: RequestBodyObject | undefined,\n  operationContext: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): ParameterGroup[] | undefined {\n  const raw = op['x-mutually-exclusive-body-groups'];\n  if (!raw || typeof raw !== 'object') return undefined;\n\n  // Collect the body schema's oneOf variant fields so we can resolve types.\n  // The body schema has been structurally rewritten to allOf: [base, { oneOf: [...] }]\n  // by the spec generator; the variant properties live inside oneOf branches.\n  // Read from the same pick `requestBody` is typed from, so a body under\n  // `application/json; charset=utf-8` or a `+json` media type resolves its\n  // members like one under plain `application/json`.\n  const bodySchema = selectRequestBodyContent(requestBody)?.schema;\n  const variantFieldSchemas = collectVariantFieldSchemas(bodySchema, componentSchemas);\n\n  const groups: ParameterGroup[] = [];\n\n  for (const [groupName, groupDef] of Object.entries(raw)) {\n    if (!groupDef || typeof groupDef !== 'object') continue;\n    if (typeof groupDef.optional !== 'boolean') continue;\n    if (!groupDef.variants || typeof groupDef.variants !== 'object') continue;\n    if (Object.keys(groupDef.variants).length === 0) continue;\n\n    const variants = Object.entries(groupDef.variants).map(([variantName, paramNames]) => {\n      if (!Array.isArray(paramNames) || paramNames.length === 0) {\n        throw new Error(\n          `Malformed x-mutually-exclusive-body-groups.${groupName}.variants.${variantName} in ${operationContext}: expected a non-empty array of parameter names.`,\n        );\n      }\n      const parameters: Parameter[] = paramNames.map((pName) => {\n        const entry = variantFieldSchemas.get(pName);\n        const fieldSchema = entry?.schema;\n        // No schema found means the body's oneOf branches don't declare this\n        // member. Falling back to `string` silently produces an SDK that\n        // type-checks against itself but misrepresents the wire contract\n        // (object-valued members become plain strings), so say so loudly.\n        if (!fieldSchema) {\n          console.warn(\n            `[oagen] Warning: x-mutually-exclusive-body-groups.${groupName}.variants.${variantName} ` +\n              `references \"${pName}\" in ${operationContext}, but no oneOf branch of the request body ` +\n              `declares that property. Falling back to type: string.`,\n          );\n        }\n        const fieldType: TypeRef = fieldSchema\n          ? schemaToTypeRef(fieldSchema, toPascalCase(pName), entry?.owner)\n          : { kind: 'primitive', type: 'string' };\n        return {\n          name: pName,\n          type: fieldType,\n          required: false, // group variant fields are always optional at the struct level\n          description: fieldSchema?.description,\n        };\n      });\n\n      // Optional variant membership: fields the caller may omit when using\n      // this variant. Only names that actually belong to the variant count —\n      // anything else in the extension is ignored rather than fatal.\n      const rawOptionalFields =\n        groupDef.optionalFields && typeof groupDef.optionalFields === 'object'\n          ? groupDef.optionalFields[variantName]\n          : undefined;\n      const optionalParameters = Array.isArray(rawOptionalFields)\n        ? rawOptionalFields.filter((name): name is string => typeof name === 'string' && paramNames.includes(name))\n        : [];\n\n      return {\n        name: variantName,\n        parameters,\n        ...(optionalParameters.length > 0 ? { optionalParameters } : {}),\n      };\n    });\n\n    groups.push({\n      name: groupName,\n      optional: groupDef.optional,\n      variants,\n    });\n  }\n\n  return groups.length > 0 ? groups : undefined;\n}\n\n/** A response placeholder for detecting a strategy from the query parameters alone. */\nconst UNKNOWN_RESPONSE: TypeRef = { kind: 'primitive', type: 'unknown' };\n\nfunction buildOperation(\n  method: HttpMethod,\n  path: string,\n  op: OperationObject,\n  pathLevelParams: RawParameterObject[],\n  pathItemDocs: PathItemDocs,\n  pathModelBaseName: string,\n  operationIdTransform?: (id: string) => string,\n  serviceName?: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  componentParameters?: Record<string, Record<string, unknown>>,\n  componentRequestBodies?: Record<string, Record<string, unknown>>,\n  componentExamples?: Record<string, Record<string, unknown>>,\n  componentHeaders?: Record<string, Record<string, unknown>>,\n  componentResponses?: Record<string, Record<string, unknown>>,\n  deferred: DeferredInlineType[] = [],\n  apiRootLength = 0,\n  servers?: ServerEntry[],\n  refSiblingDescriptions: SiblingDocs = 'override',\n  componentResponseModelNames?: ReadonlyMap<string, string>,\n  paginationHint?: unknown,\n  componentModels?: Model[],\n  registry?: ModelShapeRegistry,\n): {\n  operation: Operation;\n  inlineModels: Model[];\n  inlineModelBundles: InlineModelBundle[];\n  envelopeCompanions?: EnvelopeCompanion[];\n  /** What the shape registry records as the owner of this operation's models (see `headerOperationQualifier`). */\n  operationQualifier: string;\n} {\n  const opLabel = operationLabel(op, path, method);\n  warnOnIgnoredCallbacks(op.callbacks, opLabel);\n  const operationName = inferOperationName(method, path, op.operationId, operationIdTransform, apiRootLength);\n  // Resolve a `components/requestBodies` ref up front so body extraction, body\n  // parameter groups, and the body-ownership rule below all read one object.\n  const requestBodyObject = resolveRequestBodyRef(\n    op.requestBody,\n    componentRequestBodies,\n    opLabel,\n    refSiblingDescriptions,\n  );\n  // An operation-level parameter overrides a path-level one with the same\n  // identity — `parameterKey`: location and name, a header's name\n  // case-folded, so a path-level `X-Pet-Token` and an operation-level\n  // `x-pet-token` are one header (#295) — rather than adding a second entry.\n  // Operation params come last, so last-write-wins; Map.set keeps the\n  // original insertion position, so path-level parameter ordering is\n  // preserved.\n  const paramsByIdentity = new Map<string, ParameterObject>();\n  for (const raw of [...pathLevelParams, ...(op.parameters ?? [])]) {\n    const param = resolveParameterRef(raw, componentParameters, opLabel, refSiblingDescriptions);\n    paramsByIdentity.set(parameterKey(param.in, param.name), param);\n  }\n  const allParams = [...paramsByIdentity.values()];\n\n  const hasIdempotencyHeader = allParams.some((p) => p.in === 'header' && foldHeaderName(p.name) === 'idempotency-key');\n  // Reported here, once per parameter the operation types: `extractParams`\n  // runs per location, and the passes that re-read a parameter's schema\n  // stay silent. The idempotency header is not typed (see `extract` below),\n  // so a `content` map on it is not reported.\n  for (const param of allParams) {\n    if (param.in === 'header' && foldHeaderName(param.name) === 'idempotency-key') continue;\n    warnUnreadParameterContent(param, `Parameter \"${param.name}\" (in: ${param.in}) on ${opLabel}`);\n  }\n\n  // A parameter the spec declares both as `in: query` and as a request-body\n  // property is one value with two wire locations. On a body-carrying method\n  // it travels in the body only: duplicating it into the URL puts body-grade\n  // material (OAuth codes, client secrets) into access logs and exception\n  // traces, and emitters that surface both copies grow a second public\n  // parameter for the same field. RFC 6749 §4.1.3 puts token-request\n  // parameters in the body for the same reason. GET/DELETE keep every\n  // declared query parameter — they have no body to prefer.\n  //\n  // One carve-out: a query parameter named by `x-mutually-exclusive-parameter-groups`\n  // stays a parameter. The extension models it as one, the group resolver\n  // below looks it up in the parameter arrays, and emitters already route\n  // groups into the body on body-carrying methods, so nothing reaches the URL.\n  const groupedQueryNames = collectParameterGroupMemberNames(op);\n  const bodyOwnedNames = new Set<string>();\n  if (BODY_CARRYING_METHODS.has(method)) {\n    const bodySchema = selectRequestBodyContent(requestBodyObject)?.schema;\n    for (const name of collectBodyPropertyNames(bodySchema, componentSchemas)) {\n      if (!groupedQueryNames.has(name)) bodyOwnedNames.add(name);\n    }\n  }\n  const wireParams =\n    bodyOwnedNames.size > 0 ? allParams.filter((p) => !(p.in === 'query' && bodyOwnedNames.has(p.name))) : allParams;\n\n  // Use the service name as context so inline parameter enums get qualified\n  // names. e.g., service \"Auth\" + param \"provider\" → \"AuthProvider\".\n  const opContext = serviceName;\n  // Names this operation's models in the shape registry, and qualifies a\n  // deferred model's name when one of them is taken across operations.\n  const operationQualifier = headerOperationQualifier(op, operationName, pathModelBaseName, opContext);\n  // What the typing of a parameter, a response header or a secondary,\n  // fallback or error body reads from the operation and the spec; a schema\n  // deferred through it is typed once every operation has been read\n  // (`resolveDeferredInlineTypes`).\n  const typing: ResponseTypingContext = {\n    componentHeaders,\n    componentSchemas,\n    componentResponses,\n    serviceName: opContext,\n    operationQualifier,\n    deferred,\n    refSiblingDescriptions,\n    componentResponseModelNames,\n    registry,\n  };\n  // One location's parameters, typed by `extractParams`. A parameter whose\n  // inline schema mints a model is deferred once the responses have been\n  // read (`deferParameterModels`, after `extractResponses` below), so the\n  // model is created under a name nothing else owns and a response header\n  // the operation types keeps the name it has.\n  const pendingParams: Array<[raw: ParameterObject[], typed: Parameter[], location: ParameterObject['in']]> = [];\n  const extract = (location: ParameterObject['in'], source: ParameterObject[] = wireParams): Parameter[] => {\n    const params = extractParams(\n      source,\n      location,\n      opContext,\n      componentSchemas,\n      componentExamples,\n      opLabel,\n      refSiblingDescriptions,\n    );\n    pendingParams.push([source.filter((p) => p.in === location), params, location]);\n    return params;\n  };\n  const pathParams = extract('path');\n  const queryParams = extract('query');\n  // The idempotency header is the SDK's to inject (`injectIdempotencyKey`), not a parameter to type.\n  const headerParams = extract(\n    'header',\n    wireParams.filter((p) => !(p.in === 'header' && foldHeaderName(p.name) === 'idempotency-key')),\n  );\n  const cookieParams = extract('cookie');\n  // Keep the body-owned declarations on the operation so downstream passes\n  // (inline-enum collection, the compat surface) still see what the spec\n  // declared, even though no emitter serializes them to the URL.\n  const bodyOwnedQueryParams =\n    bodyOwnedNames.size > 0\n      ? extract(\n          'query',\n          allParams.filter((p) => p.in === 'query' && bodyOwnedNames.has(p.name)),\n        )\n      : [];\n\n  const reqBodyModels: Model[] = [];\n  const {\n    body: requestBody,\n    encoding: requestBodyEncoding,\n    contentType: requestBodyContentType,\n    description: requestBodyDescription,\n    contentTypes: requestBodyContentTypes,\n    contents: requestBodyContents,\n  } = extractRequestBody(requestBodyObject, op, pathModelBaseName, reqBodyModels, componentSchemas, opLabel, {\n    deferred,\n    operationQualifier,\n    componentSchemas,\n  });\n  // Read off the resolved body so a `components/requestBodies` ref's flag\n  // counts. Only `true` makes the body required: OpenAPI defaults the flag\n  // to `false`, and a non-boolean value is not a declaration of requiredness.\n  // Set exactly when a body is, so the two fields can be read together.\n  const requestBodyRequired = requestBody !== undefined ? requestBodyObject?.required === true : undefined;\n\n  // The page parameter's first value is read from its schema as written —\n  // `schema`, else the picked `content` entry's (`parameterTyping`) — so a\n  // `default`/`minimum` behind `allOf: [{ $ref }]` or a nullable wrapper —\n  // which the IR parameter's own `default` does not carry — still counts.\n  const querySchemas = new Map(\n    wireParams.filter((p) => p.in === 'query').map((p) => [p.name, parameterSchema(p)] as const),\n  );\n  const pageStartOf = (param: Parameter | undefined): number =>\n    derivePageStart(param, param && querySchemas.get(param.name), componentSchemas);\n\n  // Whether an override was written at all, usable or not: an envelope that\n  // ends up with no iterator is warned about only when none was, since a\n  // rejected override has already been warned about by name.\n  const overrideGiven = op['x-pagination'] !== undefined || paginationHint !== undefined;\n  // The explicit pagination override — config hint over `x-pagination` — is\n  // validated before the response is classified: `strategy: 'none'` must keep\n  // a list envelope from being unwrapped into a bare array, and an explicit\n  // `dataPath` is resolved against the response while its schema is at hand.\n  let paginationOverride = resolvePaginationOverride({ extension: op['x-pagination'], hint: paginationHint }, opLabel);\n  const paginationDisabled = paginationOverride?.hint.strategy === 'none';\n  // The pagination the query parameters alone yield, read before the\n  // response is: `UNKNOWN_RESPONSE` stands in for the response, whose item\n  // type this read never uses.\n  const paginationFromParamsAlone =\n    detectPagination(UNKNOWN_RESPONSE, queryParams, undefined, { pageStartOf }) ?? undefined;\n  // Whether the override can apply is decided here, before the response is\n  // read: one that would be rejected (a `param` the operation does not\n  // declare, no strategy from anywhere) must not keep an envelope as a\n  // wrapper that detection then reads as the list. What it is checked\n  // against is the pagination the query parameters alone yield — a\n  // parameter the operation does not declare never makes an override usable.\n  if (paginationOverride && !paginationDisabled) {\n    const resolved = resolveOverrideParams(paginationFromParamsAlone, paginationOverride.hint, queryParams);\n    if ('problem' in resolved) {\n      console.warn(`[oagen] Warning: ${paginationOverride.source} on ${opLabel}${resolved.problem}`);\n      paginationOverride = undefined;\n    }\n  }\n  // What drives the iterator, if anything: a query parameter the operation\n  // declares — the one detection found, or the one a usable override names\n  // (checked above). With neither there is nothing to page with, so a list\n  // envelope is not unwrapped for an iterator that never comes: it is kept as\n  // a plain response model, the wire shape, exactly as `strategy: 'none'`\n  // keeps it.\n  const iteratorSource: 'parameters' | 'override' | undefined = paginationDisabled\n    ? undefined\n    : paginationFromParamsAlone\n      ? 'parameters'\n      : paginationOverride\n        ? 'override'\n        : undefined;\n  const {\n    response,\n    responseHeaders,\n    responseContentTypes,\n    responseContents,\n    responseDescription,\n    responseStatusCode,\n    successResponses,\n    errors,\n    defaultResponse,\n    rangeResponses,\n    inlineModels: responseModels,\n    isPaginated,\n    dataPath: responseDataPath,\n    dataDescription: responseDataDescription,\n    itemType: responseItemType,\n    envelopeFields,\n    endOfIteration: responseEndOfIteration,\n    overrideItemType,\n    overrideProblem,\n    envelopeCompanions,\n    unpagedEnvelope,\n  } = extractResponses(op.responses, op, pathModelBaseName, path, method, componentSchemas, typing, {\n    disabled: iteratorSource === undefined,\n    dataPath: paginationDisabled ? undefined : paginationOverride?.hint.dataPath,\n    endOfIteration: paginationDisabled ? undefined : paginationOverride?.hint.endOfIteration,\n    componentModels,\n    overrideOnly: iteratorSource === 'override',\n  });\n  const inlineModels = [...responseModels, ...reqBodyModels];\n\n  // The parameters' deferred sites follow the responses' in the registry, so\n  // a response header the operation typed keeps its name (`PetsXMeta`) and a\n  // header parameter of the same name takes the location-qualified one\n  // (`PetsHeaderXMeta`), never the reverse.\n  for (const [raw, typed, location] of pendingParams) deferParameterModels(raw, typed, location, typing);\n\n  // An override the primary response cannot satisfy — a `dataPath` that\n  // reaches no array in it, an `endOfIteration` that resolves in it to no\n  // field of the fitting type — cannot type the iterator's items or would\n  // send it reading a field that is not there, so the whole override falls\n  // back to detection, as every other unusable override does. The decision\n  // was made before any body was read (`extractResponses`), so no success\n  // body was classified with it; one warning names the source, the\n  // operation and the problem.\n  if (paginationOverride && !paginationDisabled && overrideProblem !== undefined) {\n    console.warn(\n      `[oagen] Warning: ${paginationOverride.source} on ${opLabel}: ${overrideProblem} — ignoring the override`,\n    );\n    paginationOverride = undefined;\n  }\n\n  // Build structured pagination metadata from query param detection and\n  // response classification, then let the override correct or disable it.\n  const paginationFromParams = detectPagination(response, queryParams, responseDataPath, { pageStartOf });\n  // The list envelope the response was unwrapped on, whichever parameter\n  // drives the iterator: where the items are, their type, and the companions.\n  const envelope = isPaginated\n    ? {\n        dataPath: responseDataPath,\n        ...(responseDataDescription !== undefined && { dataDescription: responseDataDescription }),\n        itemType: responseItemType ?? paginatedItemType(response),\n        envelopeFields,\n      }\n    : undefined;\n  // An iterator is built around a parameter the operation declares, never an\n  // invented one: with none recognized, nothing is detected, and only an\n  // override can create the iterator — around the same envelope, which it\n  // receives below. An envelope nothing pages was kept as a plain response\n  // model above, so `isPaginated` never holds here without a parameter or a\n  // usable override. The stop field is read beside the unwrapped envelope,\n  // or beside a body kept as a wrapper under an explicit `dataPath` — a\n  // `$ref`, an envelope detection would unwrap on another array, an inline\n  // body detection did not recognize (see\n  // `ResponseClassificationOptions.dataPathOverride`).\n  const detectedPagination: PaginationMeta | undefined = paginationFromParams\n    ? {\n        ...paginationFromParams,\n        ...envelope,\n        ...(responseEndOfIteration && { endOfIteration: responseEndOfIteration }),\n      }\n    : undefined;\n  const pagination = applyPaginationOverride(detectedPagination, paginationOverride, queryParams, response, opLabel, {\n    overrideItemType,\n    // Read from the response above, so an override that creates the iterator\n    // where detection found none still iterates the envelope and stops on\n    // its stop field.\n    envelope,\n    endOfIteration: responseEndOfIteration,\n    pageStartOf,\n  });\n  // One warning per operation whose list envelope nothing pages: the cause\n  // is a missing query parameter, and the fix is to declare it or to name a\n  // declared one through an override. An override that was written and\n  // rejected has been warned about by name already.\n  if (unpagedEnvelope && !overrideGiven) {\n    console.warn(\n      `[oagen] Warning: ${opLabel} returns a list envelope but no query parameter drives an iterator ` +\n        `(${describeUndetectedPaging(queryParams)}) — keeping the body as a plain response model with no ` +\n        'pagination; declare the parameter, set x-pagination / operationHints pagination naming a query ' +\n        'parameter the operation declares, or set strategy \"none\" to accept the plain model',\n    );\n  }\n\n  // Per-operation security requirements; undefined means \"inherit ApiSpec.security\"\n  const security = extractSecurityRequirements(op.security, opLabel);\n  const tags = extractTags(op.tags);\n\n  // Extract mutually-exclusive parameter groups (query/path/header/cookie)\n  const allIRParams = [...pathParams, ...queryParams, ...headerParams, ...cookieParams];\n  const queryParamGroups = extractParameterGroups(op, allIRParams, opLabel);\n\n  // Extract mutually-exclusive body parameter groups\n  const bodyParamGroups = extractBodyParameterGroups(op, requestBodyObject, opLabel, componentSchemas);\n\n  // Merge both sources into a single parameterGroups array\n  const parameterGroups =\n    queryParamGroups || bodyParamGroups ? [...(queryParamGroups ?? []), ...(bodyParamGroups ?? [])] : undefined;\n\n  // The operation's own `summary` and `description`, or its Path Item's for\n  // each it declares none for (`resolveOperationDocs`). An empty or\n  // whitespace-only text counts as absent at either level, so it neither gets\n  // its own field nor leaks into the description as a blank first paragraph.\n  const { summary, description } = resolveOperationDocs(op, pathItemDocs);\n\n  const operation: Operation = {\n    name: operationName,\n    // Keep the summary on its own so emitters can tell it apart from the\n    // description; the key is omitted (not set to undefined) when absent.\n    ...(summary !== undefined ? { summary } : {}),\n    description,\n    // Same conditional shape as `summary`: present only when the document\n    // declares a usable link, absent (not undefined) otherwise.\n    ...externalDocsEntry(op.externalDocs),\n    httpMethod: method,\n    path,\n    // Present only when the operation's effective servers differ from the\n    // document's (see operationServers); absent, not undefined, otherwise.\n    ...(servers && { servers }),\n    pathParams,\n    queryParams,\n    bodyOwnedQueryParams: bodyOwnedQueryParams.length > 0 ? bodyOwnedQueryParams : undefined,\n    headerParams,\n    cookieParams: cookieParams.length > 0 ? cookieParams : undefined,\n    requestBody,\n    requestBodyEncoding,\n    // The picked media type's essence, what an emitter sends as Content-Type;\n    // set exactly when the body is.\n    ...(requestBodyContentType && { requestBodyContentType }),\n    // Added only when the operation has a body so bodiless operations keep\n    // their shape.\n    ...(requestBodyRequired !== undefined && { requestBodyRequired }),\n    // The body's doc text, present only when the document gives it some —\n    // the Request Body Object's own, else its picked schema's.\n    ...(requestBodyDescription !== undefined && { requestBodyDescription }),\n    // Every media type the body declares, present only when there is one —\n    // the request-side twin of `responseContentTypes` / `responseContents`.\n    ...(requestBodyContentTypes && { requestBodyContentTypes, requestBodyContents }),\n    response,\n    // Added only when present so operations without headers keep their shape.\n    ...(responseHeaders && { responseHeaders }),\n    ...(responseContentTypes && { responseContentTypes, responseContents }),\n    // Likewise only when the primary response declares a description.\n    ...(responseDescription && { responseDescription }),\n    // And only when a 2xx or 3xx response is declared at all, so the status\n    // code is present exactly when `response` was read from one.\n    ...(responseStatusCode !== undefined && { responseStatusCode }),\n    successResponses,\n    errors,\n    // Added only when the document declares them so operations without\n    // fallback responses keep their shape.\n    ...(defaultResponse && { defaultResponse }),\n    ...(rangeResponses && { rangeResponses }),\n    pagination,\n    injectIdempotencyKey: hasIdempotencyHeader,\n    deprecated: op.deprecated === true || undefined,\n    async: op['x-oagen-async'],\n    security,\n    parameterGroups,\n    // Present only when the document declares at least one usable tag, as on\n    // a webhook; absent, not undefined, otherwise.\n    ...(tags && { tags }),\n    // The Operation Object's own `x-*` keys, less the ones read into typed\n    // fields above (`OPERATION_CONSUMED_EXTENSIONS`); absent when none remain.\n    ...operationExtensionsEntry(op),\n  };\n\n  // Where the models came from, so a merge pass that must rename one — a\n  // deprecated response named like a live one, say — can qualify it by this\n  // operation and repoint only this operation's references: the response\n  // bundle owns the success bodies, the list envelope and the response\n  // headers; the request bundle owns the body. Qualified as a header model or\n  // list-envelope companion is (`GetLegacyWidgetWidget`).\n  const qualifier = toPascalCase(operationName);\n  const inlineModelBundles: InlineModelBundle[] = [];\n  // The response site is recorded even when it minted nothing: its array\n  // items may have shared another site's model (`typeInlineItems`), and the\n  // reference must follow that model's rename (`attachSharedRefs`).\n  inlineModelBundles.push({ qualifier, roots: responseTypeRefs(operation), models: responseModels });\n  if (reqBodyModels.length > 0 && requestBody) {\n    inlineModelBundles.push({ qualifier, roots: [requestBody], models: reqBodyModels, sent: true });\n  }\n\n  return { operation, inlineModels, inlineModelBundles, envelopeCompanions, operationQualifier };\n}\n\n/**\n * The type references an operation's responses own: the primary and every\n * alternate success body, the list envelope's fields and item type, and\n * every response header. Error bodies are left out: a `$ref` body names a\n * component, which a rename never touches, and an inline one is typed\n * through the deferred registry, where it is a site of its own\n * (`resolveDeferredInlineTypes`), so a rename reaches it from there.\n */\nfunction responseTypeRefs(op: Operation): TypeRef[] {\n  return [\n    op.response,\n    ...(op.successResponses ?? []).map((r) => r.type),\n    ...(op.pagination?.envelopeFields ?? []).map((f) => f.type),\n    ...(op.pagination ? [op.pagination.itemType] : []),\n    ...collectResponseHeaders(op).map((h) => h.type),\n  ];\n}\n\n/**\n * The qualifier that tells one operation's header models from another's\n * (`deferredNamingStem`'s `byOperationName` candidate), and that the shape\n * registry records as the owner of its models. An `operationId` names the\n * operation. A path-named operation uses the path-derived stem its request\n * and response models are built from, so the model name depends only on the\n * method and path and never on the derived operation name — a verb or\n * singular change in inferOperationName must not rename a generated type.\n * The stem's leading service word is dropped when it ends on a word boundary,\n * since the model name already starts with the service:\n * `Notes` + `ByIdPinPost` + `XMeta`, beside `NotesByIdPinPostResponse`.\n */\nfunction headerOperationQualifier(\n  op: OperationObject,\n  operationName: string,\n  pathModelBaseName: string,\n  serviceName: string | undefined,\n): string {\n  if (op.operationId) return toPascalCase(operationName);\n  const parent = serviceName ? toPascalCase(serviceName) : '';\n  const rest = pathModelBaseName.slice(parent.length);\n  return parent && pathModelBaseName.startsWith(parent) && /^[A-Z0-9]/.test(rest) ? rest : pathModelBaseName;\n}\n\n/** The Path Item fields an operation's doc text is read against (see `resolveOperationDocs`). */\nexport type PathItemDocs = Pick<PathItem, 'summary' | 'description'>;\n\n/** An operation's doc text as the IR carries it, under the names `Operation` and `Webhook` share. */\nexport interface OperationDocs {\n  /** The resolved `summary` alone; `undefined` when neither level has one with content. */\n  summary: string | undefined;\n  /** The combined form `buildDescription` makes of the two resolved texts; `undefined` when neither has content. */\n  description: string | undefined;\n}\n\n/**\n * The `summary` and `description` of an operation — an SDK operation's or a\n * webhook's — read from the Operation Object and, for each field it declares\n * no content for, from the Path Item it sits on: OpenAPI defines a Path\n * Item's `summary` and `description` as applying to every operation on it.\n * The two fields fall back one by one, so an operation with a `summary` of\n * its own and no `description` shows its own `summary` over the Path Item's\n * `description`. Text with content wins at either level; a value that is not\n * a string, or is blank, counts as absent at either level (`presentText`), so\n * `summary: \"\"` on the operation still takes the Path Item's. Either field is\n * `undefined` when\n * neither level gives it; the caller decides whether the key is then omitted\n * (`Webhook`) or present (`Operation.description`).\n */\nexport function resolveOperationDocs(op: OperationObject, pathItem: PathItemDocs): OperationDocs {\n  const summary = presentText(op.summary) ?? presentText(pathItem.summary);\n  const description = presentText(op.description) ?? presentText(pathItem.description);\n  return { summary, description: buildDescription(summary, description) };\n}\n\n/**\n * Combine an operation's `summary` and `description` into one doc text.\n * Empty or whitespace-only text counts as absent, so `summary: \"List pets\"`\n * with `description: \"\"` yields `\"List pets\"` rather than `\"\"`. Text that has\n * content is kept verbatim, surrounding whitespace included.\n */\nexport function buildDescription(summary: string | undefined, description: string | undefined): string | undefined {\n  const presentSummary = presentText(summary);\n  const presentDescription = presentText(description);\n  if (presentSummary && presentDescription && presentSummary !== presentDescription) {\n    return `${presentSummary}\\n\\n${presentDescription}`;\n  }\n  return presentDescription ?? presentSummary;\n}\n\n/** The text itself when it has non-whitespace content, otherwise `undefined`. */\nexport function presentText(text: string | undefined): string | undefined {\n  return typeof text === 'string' && text.trim() !== '' ? text : undefined;\n}\n\n/**\n * An operation's `tags` as the IR carries them, on an `Operation` and on a\n * `Webhook` alike: the list in document order with every entry that is not a\n * non-empty string dropped and a repeated entry folded onto its first\n * occurrence, or `undefined` when nothing remains (or the keyword is not a\n * list), so the key is omitted rather than set to `[]`. The service an\n * operation is grouped under is named from `[0]` of this same list.\n */\nexport function extractTags(tags: unknown): string[] | undefined {\n  if (!Array.isArray(tags)) return undefined;\n  const kept: string[] = [];\n  for (const tag of tags) {\n    if (typeof tag === 'string' && tag !== '' && !kept.includes(tag)) kept.push(tag);\n  }\n  return kept.length > 0 ? kept : undefined;\n}\n\n/**\n * The media types a parameter's or response header's `content` map is read\n * from, in the order the pick tries them (`selectParameterContent`). Each is\n * matched by essence — `type/subtype` with parameters stripped and case\n * folded (`mediaTypeEssence`), so `application/json; charset=utf-8` and\n * `APPLICATION/JSON` read as `application/json` — and a `+json` media type\n * is JSON. A JSON entry is read only when it declares a schema; a\n * `text/plain` entry is read with or without one, a text value the document\n * does not describe being a string. Any other media type is not read.\n */\nconst PARAMETER_CONTENT_MEDIA_TYPES: ReadonlyArray<{\n  matches: (essence: string) => boolean;\n  schemaRequired: boolean;\n}> = [\n  { matches: (essence) => essence === 'application/json', schemaRequired: true },\n  { matches: (essence) => essence.endsWith('+json'), schemaRequired: true },\n  { matches: (essence) => essence === 'text/plain', schemaRequired: false },\n];\n\n/** The `content` entry a parameter or response header is read from: the key as written and its Media Type Object. */\nexport interface SelectedParameterContent {\n  /** The `content` key the entry was read from, exactly as written (`application/json; charset=utf-8`). */\n  contentType: string;\n  media: ParameterMediaTypeObject;\n}\n\n/**\n * Pick the `content` entry a parameter or response header is typed from, by\n * media type essence in the fixed order of `PARAMETER_CONTENT_MEDIA_TYPES`:\n * `application/json`, then a `+json` media type — each only with a schema —\n * then `text/plain`. Within one tier the first matching key in document\n * order wins. OAS allows the map one entry, so the order decides only for a\n * document that declares more. `undefined` when there is no map, or none of\n * its media types is read; `warnUnreadParameterContent` reports the latter.\n */\nexport function selectParameterContent(\n  content: Record<string, ParameterMediaTypeObject> | undefined,\n): SelectedParameterContent | undefined {\n  if (!content) return undefined;\n  const entries = Object.entries(content);\n  for (const { matches, schemaRequired } of PARAMETER_CONTENT_MEDIA_TYPES) {\n    const match = entries.find(\n      ([contentType, media]) => matches(mediaTypeEssence(contentType)) && (!schemaRequired || media?.schema),\n    );\n    if (match) return { contentType: match[0], media: match[1] ?? {} };\n  }\n  return undefined;\n}\n\n/** What types a parameter or response header: its schema, and the Media Type Object the schema was read from under `content`. */\nexport interface ParameterTyping {\n  /** Absent when the declaration types nothing: the value is a string. */\n  schema?: SchemaObject;\n  /** The picked `content` entry, only when the declaration has no `schema` and the map is read. */\n  media?: ParameterMediaTypeObject;\n  /** The `content` key `media` sits under, as written; set exactly when `media` is. */\n  contentType?: string;\n}\n\n/**\n * The schema that types a parameter or response header: the declaration's\n * `schema` when it has one, else the schema of the `content` entry\n * `selectParameterContent` picks, with that entry's Media Type Object\n * beside it for the examples it may carry. `schema` is absent — and the\n * value a string — when the declaration has neither, when the picked\n * `text/plain` entry declares no schema, or when nothing in the map is read.\n * A `schema` beside a `content` map wins and the map is not consulted.\n * Every pass that asks what a parameter's schema is reads it through this\n * one resolution: the typing (`extractParams`), the model deferral\n * (`deferParameterModels`), the page-start read, a webhook's parameter mint\n * and a response header's typing (`extractResponseHeaders`) — so a\n * parameter declared either way is typed, and mints, by one rule.\n */\nexport function parameterTyping(declaration: SchemaOrContent): ParameterTyping {\n  if (declaration.schema) return { schema: declaration.schema };\n  const picked = selectParameterContent(declaration.content);\n  return picked ? { schema: picked.media.schema, media: picked.media, contentType: picked.contentType } : {};\n}\n\n/** The schema `parameterTyping` resolves, alone. */\nexport function parameterSchema(declaration: SchemaOrContent): SchemaObject | undefined {\n  return parameterTyping(declaration).schema;\n}\n\n/**\n * Warn that a parameter's or response header's `content` map is not read:\n * it declares no `schema`, at least one media type, and\n * `selectParameterContent` picks none, so the value is typed as a string.\n * Called once per site — for each operation parameter where the operation's\n * parameters are resolved (`buildOperation`), for each webhook parameter\n * where the webhook's entry is built (the mint itself runs twice), and for\n * each response header as it is typed — while `extractParams` and the\n * passes that re-read the schema stay silent. An empty map declares nothing\n * and is not reported; a map beside a `schema` is not consulted and not\n * reported either.\n */\nexport function warnUnreadParameterContent(declaration: SchemaOrContent, subject: string): void {\n  if (declaration.schema) return;\n  const declared = Object.keys(declaration.content ?? {});\n  if (declared.length === 0 || selectParameterContent(declaration.content)) return;\n  console.warn(\n    `[oagen] Warning: ${subject} is typed as a string: none of its content media types (${declared.join(', ')}) ` +\n      `is read. A parameter or response header declared with content is read from application/json or a +json ` +\n      `media type when the entry declares a schema, and from text/plain with or without one, parameters and ` +\n      `case aside.`,\n  );\n}\n\nexport function extractParams(\n  params: ParameterObject[],\n  location: 'path' | 'query' | 'header' | 'cookie',\n  operationContext?: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  componentExamples?: Record<string, Record<string, unknown>>,\n  opLabel?: string,\n  siblingDocs: SiblingDocs = 'override',\n): Parameter[] {\n  return params\n    .filter((p) => p.in === location)\n    .map((p) => {\n      // The schema that types the parameter — `schema`, else the picked\n      // `content` entry's (`parameterTyping`) — and that entry's Media Type\n      // Object for the examples it may carry. Every read below goes through\n      // `schema`, so a parameter declared either way is typed by one rule.\n      const { schema, media, contentType } = parameterTyping(p);\n      const refTarget = resolveComponentSchemaRef(schema, componentSchemas);\n      const exampleContext = `parameter \"${p.name}\" in ${opLabel ?? location}`;\n      // Each level is resolved on its own — the parameter's declaration, the\n      // Media Type Object its schema was read from (when it was), the schema,\n      // then the component the schema refs — so a schema-level `example`\n      // can't mask the parameter's own `examples` map, and an explicit `null`\n      // at any level is kept rather than fallen through.\n      const { example, examples } = resolveExamples([\n        {\n          example: p.example,\n          examples: exampleObjectValues(p.examples, componentExamples, exampleContext, siblingDocs),\n        },\n        ...(media\n          ? [\n              {\n                example: media.example,\n                examples: exampleObjectValues(media.examples, componentExamples, exampleContext, siblingDocs),\n              },\n            ]\n          : []),\n        { example: schema?.example, examples: nonEmptyExamples(schema?.examples) },\n        { example: refTarget?.example, examples: nonEmptyExamples(refTarget?.examples) },\n      ]);\n      // Like default/example, fall back per value: the `$ref` target's keywords\n      // sit under the parameter's own, so `{ $ref: Limit, minimum: 5 }` narrows\n      // one bound without discarding the target's others. The alias also becomes\n      // a fieldless model, but a parameter should be readable on its own.\n      const own = schema ? extractConstraints(schema) : undefined;\n      const inherited = refTarget ? extractConstraints(refTarget) : undefined;\n      const constraints = own && inherited ? { ...inherited, ...own } : (own ?? inherited);\n      // The schema's link, else the `$ref` target's — the same fallback chain\n      // `description` and `deprecated` follow, with an unusable entry at one\n      // level falling through to the next as an empty description does. A\n      // Parameter Object declares no `externalDocs` of its own.\n      const externalDocs = readExternalDocs(schema?.externalDocs) ?? readExternalDocs(refTarget?.externalDocs);\n      return {\n        name: p.name,\n        // Typed under the name the parameter is compared by (`foldParameterName`:\n        // a header's lower-cased), so the inline enum or model its schema mints\n        // keeps its name when the header's case changes (#295); `name` above\n        // stays as written.\n        type: schema\n          ? schemaToTypeRef(\n              schema,\n              foldParameterName(p.in, p.name),\n              operationContext ? toPascalCase(operationContext) : undefined,\n            )\n          : ({ kind: 'primitive', type: 'string' } as TypeRef),\n        required: p.required ?? false,\n        description: firstDescription(p.description, schema?.description, refTarget?.description),\n        deprecated: p.deprecated === true || schema?.deprecated === true || refTarget?.deprecated === true || undefined,\n        ...(externalDocs ? { externalDocs } : {}),\n        default: schema?.default ?? refTarget?.default,\n        example,\n        ...(examples ? { examples } : {}),\n        style: p.style as Parameter['style'],\n        explode: p.explode,\n        // The media type the value is serialized in, for a parameter read\n        // from `content`; a `schema` parameter is serialized by style/explode.\n        ...(contentType !== undefined ? { contentType } : {}),\n        ...(constraints ? { constraints } : {}),\n      };\n    });\n}\n\n/**\n * First non-empty description in precedence order. A parameter that declares\n * `description: \"\"` is treated as undocumented so its schema's text still\n * surfaces, and the result is `undefined` rather than `\"\"` when nothing in\n * the chain is documented.\n */\nfunction firstDescription(...candidates: Array<string | undefined>): string | undefined {\n  return candidates.find((candidate) => typeof candidate === 'string' && candidate.length > 0);\n}\n\n/**\n * Flatten a parameter's `examples` map of Example Objects to the inline\n * values it carries, in document order. A `$ref` entry is resolved against\n * `components.examples` first (see `resolveExampleRef`). Entries that point\n * elsewhere (`externalValue`) or have no `value` are skipped; `null` is a\n * legitimate value and kept. Returns undefined when nothing remains so the\n * caller can fall through to the schema's `examples`.\n */\nfunction exampleObjectValues(\n  examples: Record<string, ExampleObject> | undefined,\n  componentExamples: Record<string, Record<string, unknown>> | undefined,\n  context: string,\n  siblingDocs: SiblingDocs = 'override',\n): unknown[] | undefined {\n  if (!examples || typeof examples !== 'object' || Array.isArray(examples)) return undefined;\n  const values: unknown[] = [];\n  for (const raw of Object.values(examples)) {\n    const entry = resolveExampleRef(raw, componentExamples, context, siblingDocs);\n    if (!entry || typeof entry !== 'object') continue;\n    if (entry.externalValue !== undefined || entry.value === undefined) continue;\n    values.push(entry.value);\n  }\n  return values.length > 0 ? values : undefined;\n}\n\n/**\n * Follow an Example Object's `$ref` into `components.examples`, including a\n * component that is itself a `$ref`, with a cycle guard. The bundler keeps\n * refs (`dereference: false`), so without this every `$ref` entry would be\n * dropped and a map made only of refs would silently yield nothing — the\n * parameter would then take its `examples` from the schema instead of the\n * values the document points at. A ref that can't be resolved is skipped\n * with a warning rather than failing the parse: a missing example is a doc\n * gap, not a broken API surface.\n */\nfunction resolveExampleRef(\n  raw: ExampleObject | undefined,\n  componentExamples: Record<string, Record<string, unknown>> | undefined,\n  context: string,\n  siblingDocs: SiblingDocs = 'override',\n): ExampleObject | undefined {\n  // An entry that is not an object is no example; the caller skips it.\n  if (!raw || typeof raw !== 'object') return undefined;\n  // The walk every Reference Object takes (`followReference`): a `summary`\n  // or `description` written beside a ref overrides the component's under\n  // `'override'` (OAS 3.1) and is ignored under `'ignore'` (OAS 3.0), though\n  // only the example's `value` is read into the IR (`exampleObjectValues`).\n  const followed = followReference<ExampleObject>(raw, 'examples', componentExamples, siblingDocs);\n  if (followed.outcome === 'circular') {\n    console.warn(`[oagen] Warning: Circular example $ref chain starting at \"${followed.ref}\" on ${context}; skipping`);\n    return undefined;\n  }\n  if (followed.outcome !== 'resolved') {\n    console.warn(`[oagen] Warning: Unresolved example $ref \"${followed.ref}\" on ${context}; skipping`);\n    return undefined;\n  }\n  return followed.value;\n}\n\n/**\n * Collect the property schemas of every `oneOf` branch reachable from a request\n * body schema, keyed by property name. These are the candidate members of a\n * mutually-exclusive body group.\n *\n * The bundler runs with `dereference: false`, so the body schema is very often\n * a bare `{ $ref: '#/components/schemas/XDto' }` and the `allOf`/`oneOf`\n * composition that actually declares the variant properties lives on the\n * component. Walking without resolving refs finds nothing, and every group\n * member then falls back to `string` — an SDK that compiles but types\n * object-valued members (e.g. a connection's `saml_options`) as plain strings.\n *\n * Composition keywords nest and may themselves be refs, so resolve and recurse\n * at each level. `seen` guards against a schema that (directly or transitively)\n * refs itself.\n */\nfunction collectVariantFieldSchemas(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  owner: string | undefined = undefined,\n  out: Map<string, VariantFieldSchema> = new Map(),\n  seen: Set<string> = new Set(),\n): Map<string, VariantFieldSchema> {\n  if (!schema) return out;\n\n  const ref = (schema as { $ref?: string }).$ref;\n  if (ref) {\n    if (seen.has(ref)) return out;\n    seen.add(ref);\n    const match = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n    const target = match && componentSchemas ? componentSchemas[match[1]] : undefined;\n    // Descending into a component makes it the owner of everything below, so\n    // inline members get the same synthesized names the model emitter gives\n    // them (`CreateUser` + `password_hash_type` -> CreateUserPasswordHashType).\n    const nextOwner = match ? resolveSchemaName(match[1]) : owner;\n    return collectVariantFieldSchemas(target, componentSchemas, nextOwner, out, seen);\n  }\n\n  // A `oneOf` branch is the group-variant carrier: its properties are the\n  // members. Record them, then keep descending — branches nest in real specs.\n  for (const variant of schema.oneOf ?? []) {\n    const variantRef = (variant as { $ref?: string }).$ref;\n    const refMatch = variantRef ? /^#\\/components\\/schemas\\/(.+)$/.exec(variantRef) : null;\n    const resolved = resolveSchemaRefObject(variant, componentSchemas) ?? variant;\n    const variantOwner = refMatch ? resolveSchemaName(refMatch[1]) : owner;\n    for (const [name, fieldSchema] of Object.entries(resolved.properties ?? {})) {\n      if (fieldSchema) out.set(name, { schema: fieldSchema, owner: variantOwner });\n    }\n    collectVariantFieldSchemas(variant, componentSchemas, owner, out, seen);\n  }\n\n  for (const sub of schema.allOf ?? []) collectVariantFieldSchemas(sub, componentSchemas, owner, out, seen);\n  for (const sub of schema.anyOf ?? []) collectVariantFieldSchemas(sub, componentSchemas, owner, out, seen);\n\n  return out;\n}\n\n/** A group member's schema plus the component that owns it, for inline naming. */\ninterface VariantFieldSchema {\n  schema: SchemaObject;\n  owner: string | undefined;\n}\n\n/** Resolve `{ $ref: '#/components/schemas/X' }` to its component, else undefined. */\nfunction resolveSchemaRefObject(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): SchemaObject | undefined {\n  if (!schema || !componentSchemas) return undefined;\n  const ref = (schema as { $ref?: string }).$ref;\n  if (!ref) return undefined;\n  const match = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n  if (!match) return undefined;\n  return componentSchemas[match[1]];\n}\n\nexport type RequestBodyEncoding = 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text';\n\n/** HTTP methods whose request body is the primary parameter carrier. */\nconst BODY_CARRYING_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>(['post', 'put', 'patch']);\n\n/**\n * The media types a request body is read from, in the order the pick tries\n * them (`selectRequestBodyContent`). Each is matched by essence — `type/subtype`\n * with parameters stripped and case folded (`mediaTypeEssence`), so\n * `application/json; charset=utf-8`, `APPLICATION/JSON` and\n * `multipart/form-data; boundary=x` read as their bare types — and a `+json`\n * media type (`application/vnd.api+json`, `application/merge-patch+json`) is\n * JSON. A JSON or form body is read only when it declares a schema, so an\n * `application/json` entry without one yields to a later media type that has\n * one; a binary or text body may legitimately declare none.\n */\nconst REQUEST_BODY_MEDIA_TYPES: ReadonlyArray<{\n  matches: (essence: string) => boolean;\n  encoding: RequestBodyEncoding;\n  schemaRequired: boolean;\n}> = [\n  // The one JSON rule requests and responses share (`isJsonMediaType`), in\n  // the order `jsonResponseSchema` applies it: `application/json` itself\n  // first, then any `+json` type.\n  { matches: isPlainJsonMediaType, encoding: 'json', schemaRequired: true },\n  {\n    matches: (essence) => isJsonMediaType(essence) && !isPlainJsonMediaType(essence),\n    encoding: 'json',\n    schemaRequired: true,\n  },\n  { matches: (essence) => essence === 'multipart/form-data', encoding: 'form-data', schemaRequired: true },\n  {\n    matches: (essence) => essence === 'application/x-www-form-urlencoded',\n    encoding: 'form-urlencoded',\n    schemaRequired: true,\n  },\n  { matches: (essence) => essence === 'application/octet-stream', encoding: 'binary', schemaRequired: false },\n  { matches: (essence) => essence === 'text/plain', encoding: 'text', schemaRequired: false },\n];\n\n/** The wire encoding a media type implies by essence (`REQUEST_BODY_MEDIA_TYPES`); `undefined` for one the pick never reads. */\nfunction requestBodyEncodingOf(contentType: string): RequestBodyEncoding | undefined {\n  const essence = mediaTypeEssence(contentType);\n  return REQUEST_BODY_MEDIA_TYPES.find(({ matches }) => matches(essence))?.encoding;\n}\n\n/**\n * The type of a request content entry that declares no schema, by media type\n * essence: a binary string for `application/octet-stream`, a string for\n * `text/plain` (`schemalessRequestBodyType`), and `unknown` for anything\n * else — a JSON or form media type included, since the pick reads those only\n * with a schema. How a secondary entry of `requestBodyContents` is typed, on\n * an operation and on a webhook alike.\n */\nexport function schemalessRequestContentType(contentType: string): TypeRef {\n  const encoding = requestBodyEncodingOf(contentType);\n  return (encoding && schemalessRequestBodyType(encoding)) ?? { kind: 'primitive', type: 'unknown' };\n}\n\n/** The content entry a request body is read from: the key as written, its essence, its wire encoding and its schema. */\nexport interface SelectedRequestBodyContent {\n  /** The `content` key the body was read from, exactly as written (`application/json; charset=utf-8`). */\n  contentType: string;\n  /** The essence of `contentType` (`application/json`): what an emitter sends as the `Content-Type` (`Operation.requestBodyContentType`). */\n  essence: string;\n  encoding: RequestBodyEncoding;\n  /** Absent only for a binary or text body that declares none. */\n  schema?: SchemaObject;\n}\n\n/**\n * Pick the content entry a request body is read from, by media type essence\n * in the fixed order of `REQUEST_BODY_MEDIA_TYPES`: `application/json`, then\n * a `+json` media type, then `multipart/form-data`, then\n * `application/x-www-form-urlencoded` — each only with a schema — then\n * `application/octet-stream`, then `text/plain`. Within one tier the first\n * matching key in document order wins. `undefined` when the body declares no\n * content, or none of its media types is read; `warnUnreadRequestBody`\n * reports the latter. Every pass that asks what the body is — the body\n * extractor, the body-owned query names, the const prefixes, the body\n * parameter groups, a webhook payload — reads it through this one pick.\n */\nexport function selectRequestBodyContent(body: RequestBodyObject | undefined): SelectedRequestBodyContent | undefined {\n  const content = body?.content;\n  if (!content) return undefined;\n  const entries = Object.entries(content);\n  for (const { matches, encoding, schemaRequired } of REQUEST_BODY_MEDIA_TYPES) {\n    const match = entries.find(\n      ([contentType, media]) => matches(mediaTypeEssence(contentType)) && (!schemaRequired || media?.schema),\n    );\n    if (match) {\n      return { contentType: match[0], essence: mediaTypeEssence(match[0]), encoding, schema: match[1]?.schema };\n    }\n  }\n  return undefined;\n}\n\n/**\n * Warn that a request body is not read as `requestBody`: it declares at\n * least one media type and `selectRequestBodyContent` reads none, so\n * `requestBody` and `requestBodyEncoding` stay unset and the body reaches an\n * emitter through `requestBodyContents` alone. Called once per operation\n * (`extractRequestBody`) and once per webhook (where its entry is built: a\n * webhook is minted twice, so the mint itself must not report), while the\n * passes that re-read the pick for an operation (the body-owned query names,\n * the const prefixes, the body parameter groups) stay silent — so such a\n * body is reported once, and never silently. A body with no `content`, or an\n * empty map, declares nothing and is not reported.\n */\nexport function warnUnreadRequestBody(body: RequestBodyObject | undefined, label: string): void {\n  const declared = Object.keys(body?.content ?? {});\n  if (declared.length === 0 || selectRequestBodyContent(body)) return;\n  console.warn(\n    `[oagen] Warning: Request body of ${label} is not read as requestBody: none of its media types ` +\n      `(${declared.join(', ')}) is one the parser reads — application/json or a +json media type, ` +\n      `multipart/form-data or application/x-www-form-urlencoded with a schema, application/octet-stream or ` +\n      `text/plain with or without one, parameters and case aside. It is carried in requestBodyContents only.`,\n  );\n}\n\n/**\n * The doc text an operation or a webhook carries for its request body\n * (`Operation.requestBodyDescription`, `Webhook.requestBodyDescription`): the\n * Request Body Object's own `description` — `body` is read after a\n * `components/requestBodies` `$ref` is resolved — when it has non-whitespace\n * content, else the `description` written on the schema of the content entry\n * the pick reads (`selected`, from `selectRequestBodyContent`), as it stands\n * there: a `$ref` is not followed, so a component's text stays on its model,\n * while a `description` written beside the `$ref` is read, as a field reads\n * one. `undefined` when neither has content; a body none of whose media\n * types is read has no `selected` and carries its own text alone. The text\n * is kept verbatim. Every reader of a body — the operation extractor and the\n * webhook builder — takes the body's doc text from here.\n */\nexport function requestBodyDescriptionOf(\n  body: RequestBodyObject | undefined,\n  selected: SelectedRequestBodyContent | undefined,\n): string | undefined {\n  return presentText(body?.description) ?? presentText(selected?.schema?.description);\n}\n\n/**\n * The type of a picked request body that declares no schema: a binary body is\n * a binary string, a text body a string. A JSON or form body is picked only\n * with a schema (`REQUEST_BODY_MEDIA_TYPES`), so for those encodings this is\n * never reached and returns `undefined`.\n */\nexport function schemalessRequestBodyType(encoding: RequestBodyEncoding): TypeRef | undefined {\n  if (encoding === 'binary') return { kind: 'primitive', type: 'string', format: 'binary' };\n  if (encoding === 'text') return { kind: 'primitive', type: 'string' };\n  return undefined;\n}\n\n/** Parameter names referenced by any `x-mutually-exclusive-parameter-groups` variant. */\nfunction collectParameterGroupMemberNames(op: OperationObject): Set<string> {\n  const names = new Set<string>();\n  const raw = op['x-mutually-exclusive-parameter-groups'];\n  if (!raw || typeof raw !== 'object') return names;\n  // Malformed shapes are left for extractParameterGroups to report.\n  for (const groupDef of Object.values(raw)) {\n    const variants = groupDef && typeof groupDef === 'object' ? groupDef.variants : undefined;\n    if (!variants || typeof variants !== 'object') continue;\n    for (const members of Object.values(variants)) {\n      if (!Array.isArray(members)) continue;\n      for (const member of members) if (typeof member === 'string') names.add(member);\n    }\n  }\n  return names;\n}\n\n/**\n * Every property name a request body is guaranteed to accept, following\n * `$ref`s and descending through composition. `allOf` members all apply, so\n * their properties union. `oneOf` / `anyOf` alternatives are choices, so only\n * a property every non-null alternative declares counts — otherwise a caller\n * on another branch would have no slot for the value in either the body or\n * the query. Used to decide which `in: query` declarations are body-owned.\n */\nfunction collectBodyPropertyNames(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  seen: ReadonlySet<string> = new Set(),\n): Set<string> {\n  if (!schema) return new Set();\n\n  const ref = (schema as { $ref?: string }).$ref;\n  if (ref) {\n    // Cycle guard is per path: the same component may legitimately appear in\n    // sibling branches and must count for each of them.\n    if (seen.has(ref)) return new Set();\n    return collectBodyPropertyNames(\n      resolveSchemaRefObject(schema, componentSchemas),\n      componentSchemas,\n      new Set([...seen, ref]),\n    );\n  }\n\n  const names = new Set(Object.keys(schema.properties ?? {}));\n  for (const sub of schema.allOf ?? []) {\n    for (const name of collectBodyPropertyNames(sub, componentSchemas, seen)) names.add(name);\n  }\n  for (const alternatives of [schema.oneOf, schema.anyOf]) {\n    const branches = (alternatives ?? []).filter((alt) => alt.type !== 'null');\n    if (branches.length === 0) continue;\n    let common: Set<string> | undefined;\n    for (const branch of branches) {\n      const branchNames = collectBodyPropertyNames(branch, componentSchemas, seen);\n      common = common ? new Set([...common].filter((name) => branchNames.has(name))) : branchNames;\n    }\n    for (const name of common ?? []) names.add(name);\n  }\n  return names;\n}\n\n/** What request body typing needs beyond the body: where deferred schemas go and how their names are qualified. */\ninterface RequestTypingContext {\n  /** Collects every secondary-body schema, named after the operations loop (`resolveDeferredInlineTypes`). */\n  deferred: DeferredInlineType[];\n  /** Qualifies a name taken across operations (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /** Lets inline models resolve `$ref` siblings and augmentations the way fields do. */\n  componentSchemas?: Record<string, SchemaObject>;\n}\n\n/** The request body an operation carries: the picked entry typed, every declared media type with its type, and its doc text. */\ninterface ExtractedRequestBody {\n  body?: TypeRef;\n  encoding?: RequestBodyEncoding;\n  /** The body's doc text (`Operation.requestBodyDescription`, `requestBodyDescriptionOf`); absent when there is none. */\n  description?: string;\n  /** The picked entry's essence (`Operation.requestBodyContentType`); set exactly when `body` is. */\n  contentType?: string;\n  contentTypes?: string[];\n  contents?: RequestBodyContent[];\n}\n\n/**\n * The name an operation's inline request body is materialized under:\n * `<Op>Request` from the `operationId` (`operationIdModelName`), else the\n * path-derived prefix plus `Request` (see derivePathModelBaseName) so two\n * operations without an `operationId` never share one inline body model —\n * every operationId-less body used to be `RequestBody`, and only the largest\n * survived deduplication, leaving every other operation pointing at a model\n * with someone else's fields.\n */\nfunction requestModelName(op: OperationObject | undefined, pathModelBaseName: string): string {\n  return op?.operationId ? operationIdModelName(op.operationId, 'Request') : pathModelBaseName + 'Request';\n}\n\n/**\n * The stem a secondary request body's model is named from: the primary\n * body's name without its `Request` suffix, followed by the media type and\n * `Request` — `ReplaceWidgetTextCsvRequest` beside `ReplaceWidgetRequest` —\n * the way a secondary response body's stem is the primary response's name\n * without `Response`.\n */\nfunction requestModelStem(op: OperationObject | undefined, pathModelBaseName: string): string {\n  return requestModelName(op, pathModelBaseName).replace(/Request$/, '');\n}\n\n/**\n * Read an operation's request body: the content entry the pick chooses\n * (`selectRequestBodyContent`) typed as `body` with its `encoding`, and every\n * media type the body declares as `contentTypes` / `contents`, the picked\n * entry sharing `body`'s TypeRef (`extractRequestBodyContents`), and the\n * body's doc text as `description` (`requestBodyDescriptionOf`). A body none\n * of whose media types is read is reported once and carried in `contents`\n * alone, with its own `description` when it declares one.\n */\nfunction extractRequestBody(\n  body: RequestBodyObject | undefined,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  inlineModels: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  opLabel: string,\n  ctx: RequestTypingContext,\n): ExtractedRequestBody {\n  const selected = selectRequestBodyContent(body);\n  if (!selected) warnUnreadRequestBody(body, opLabel);\n  const primary = selected ? typeRequestBody(selected, op, pathModelBaseName, inlineModels, componentSchemas) : {};\n  const contents = extractRequestBodyContents(\n    body?.content,\n    selected?.contentType,\n    primary.body,\n    requestModelStem(op, pathModelBaseName),\n    ctx,\n  );\n  const description = requestBodyDescriptionOf(body, selected);\n  return { ...primary, ...contents, ...(description !== undefined && { description }) };\n}\n\n/**\n * Read a request body's `content` map into the media types it declares — in\n * document order and verbatim, parameters and vendor suffixes included — with\n * a type for each, as `extractResponseContents` reads a response's. The entry\n * for `primaryContentType` (the one the pick read `primaryType` from) carries\n * that very TypeRef; every other entry goes through\n * `typeSecondaryRequestContent`. `undefined` when the body declares no media\n * type at all, so the caller leaves both keys off.\n */\nfunction extractRequestBodyContents(\n  content: Record<string, { schema?: SchemaObject }> | undefined,\n  primaryContentType: string | undefined,\n  primaryType: TypeRef | undefined,\n  stem: string,\n  ctx: RequestTypingContext,\n): { contentTypes: string[]; contents: RequestBodyContent[] } | undefined {\n  if (!content) return undefined;\n  const contentTypes = Object.keys(content);\n  if (contentTypes.length === 0) return undefined;\n  const contents = contentTypes.map((contentType) => {\n    const entry: RequestBodyContent = { contentType, type: { kind: 'primitive', type: 'unknown' } };\n    entry.type =\n      primaryType !== undefined && contentType === primaryContentType\n        ? primaryType\n        : typeSecondaryRequestContent(contentType, content[contentType]?.schema, stem, ctx, entry, contentTypes);\n    return entry;\n  });\n  return { contentTypes, contents };\n}\n\n/**\n * Type a media type the request body pick did not choose, as it would be\n * typed were it the only one declared: from its schema when it has one — an\n * inline object materialized as `<Op><MediaType>Request`\n * (`ReplaceWidgetTextCsvRequest`), named once every primary model is known\n * (`resolveDeferredInlineTypes`), so the schema is deferred and the\n * placeholder returned here is filled in then — else as\n * `schemalessRequestContentType` types it. The media type's fragment is\n * decided among its `siblings`, the body's content keys\n * (`mediaTypeNameFragment`): two spellings of one media type declared side\n * by side take separate names by their parameters, and case-only spellings\n * that derive one name are told apart by the registry.\n */\nfunction typeSecondaryRequestContent(\n  contentType: string,\n  schema: SchemaObject | undefined,\n  stem: string,\n  ctx: RequestTypingContext,\n  target: RequestBodyContent,\n  siblings: readonly string[],\n): TypeRef {\n  if (!schema) return schemalessRequestContentType(contentType);\n  ctx.deferred.push({\n    kind: 'request',\n    schema,\n    name: `${stem}${mediaTypeNameFragment(contentType, siblings)}Request`,\n    operationQualifier: ctx.operationQualifier,\n    componentSchemas: ctx.componentSchemas,\n    targets: [target],\n  });\n  return target.type;\n}\n\n/**\n * The picked content entry typed as `Operation.requestBody`, with its\n * encoding and its essence (`Operation.requestBodyContentType`), and its\n * inline models pushed to `inlineModels`.\n */\nfunction typeRequestBody(\n  selected: SelectedRequestBodyContent,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  inlineModels: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): { body?: TypeRef; encoding?: RequestBodyEncoding; contentType?: string } {\n  const typed = typePickedRequestBody(selected, op, pathModelBaseName, inlineModels, componentSchemas);\n  return typed ? { body: typed, encoding: selected.encoding, contentType: selected.essence } : {};\n}\n\n/** The picked content entry's type: a primitive for a schema-less binary or text body, else typed from its schema. */\nfunction typePickedRequestBody(\n  selected: SelectedRequestBodyContent,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  inlineModels: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): TypeRef | undefined {\n  let schema = selected.schema;\n\n  // Only a binary or text pick comes without a schema; it is a primitive.\n  if (!schema) return schemalessRequestBodyType(selected.encoding);\n\n  const contextName = requestModelName(op, pathModelBaseName);\n\n  // `properties` written beside a typing `allOf`/`oneOf`/`anyOf` are folded\n  // into the composition, as `schemaToTypeRef` and the field extractor read\n  // them (`foldSiblingProperties`), so the body is read the one way a field\n  // of the same schema is: the object branch below reads `properties` first\n  // and would otherwise drop the composition. The variants that cannot take\n  // the properties are reported on the body as written, under the body's\n  // name, since the fold leaves `schemaToTypeRef` nothing to report.\n  warnOnUncarriedProperties(schema, contextName, undefined);\n  schema = foldSiblingProperties(schema);\n\n  // A discriminated-union request body (`oneOf` + an explicit `discriminator`)\n  // compiles to a `oneOf` that code generators can't spread into named method\n  // arguments — the caller is handed an opaque union and the generated snippets\n  // carry no body fields. When every variant is an inline object pinned by a\n  // string-const discriminator, the union is equivalent to a single object, so\n  // fold it into that object and let the normal object path below emit\n  // ergonomic, spread-able arguments. See flattenDiscriminatedUnionBody.\n  if (schema.oneOf && schema.discriminator) {\n    const merged = flattenDiscriminatedUnionBody(schema);\n    if (merged) schema = merged;\n  }\n\n  // If the request body is an inline object with properties, extract it as a\n  // model. An empty `properties: {}` beside a composition that types the\n  // body is not its object (`composedWithoutFields`): the `oneOf` branch or\n  // the fall-through reads the composition, as for a response body.\n  if (schema.properties && !composedWithoutFields(schema) && (schema.type === 'object' || !schema.type)) {\n    const requiredSet = new Set(schema.required ?? []);\n    const siblings = collectProperties(schema);\n    const fields: Field[] = [];\n    for (const [fieldName, fieldSchema] of Object.entries(schema.properties)) {\n      if (!fieldSchema) continue;\n      fields.push(buildFieldFromSchema(fieldName, fieldSchema, contextName, requiredSet, componentSchemas, siblings));\n    }\n    inlineModels.push({\n      name: contextName,\n      description: schema.description,\n      ...externalDocsEntry(schema.externalDocs),\n      fields,\n      ...deprecatedEntry(schema),\n      ...constraintsEntry(schema),\n      ...schemaExtensionsEntry(schema),\n    });\n    // Nested inline objects (e.g. a `user` property that is itself an inline\n    // object) are referenced by name from the fields above but are not emitted\n    // by this branch. Recurse to materialize them, matching how component\n    // schemas are handled in extractInlineModelsFromSchemas — otherwise the\n    // generated body model references a model that never gets generated.\n    extractInlineModelsFromProperties(schema, inlineModels, contextName, componentSchemas);\n    return { kind: 'model', name: contextName };\n  }\n\n  // A nullable body (`oneOf: [object, null]`) is one schema: the model built\n  // from its object branch takes the wrapper's `deprecated` and limits, as\n  // every other nullable unwrap gives it (`collapsedNullableBranch`). The\n  // null branch still makes the body nullable below. A multi-variant union,\n  // nullable or not, is not collapsed: every variant is built as written. A\n  // nullable wrapper around one branch that is not an inline object — an\n  // array (`oneOf: [{ items }, { type: 'null' }]`), a `$ref`, a primitive —\n  // is not a union to build: it takes the fall-through, where\n  // `schemaToTypeRef` types it as it types the same wrapper on a field or a\n  // parameter (`nullable<CreatePetsRequest[]>`, `nullable<Pet>`) and the\n  // array's inline items are named from the body (`CreatePetsRequest`), the\n  // way `type: ['array', 'null']` and `nullable: true` already are.\n  const branch = collapsedNullableBranch(schema);\n\n  // If the request body is a oneOf, extract each variant as an inline model\n  // and build a union type pointing to them by name.\n  if (schema.oneOf && (branch === undefined || isInlineObjectSchema(branch))) {\n    const variants: TypeRef[] = [];\n    // The inline object variants of this union and the names its const-less\n    // variants have taken so far, for `deriveOneOfVariantName`.\n    const inlineObjectVariants = schema.oneOf.filter(\n      (v) => !v.$ref && v.properties && (v.type === 'object' || !v.type),\n    );\n    const contentNamed: string[] = [];\n\n    // The inline object variants are named and built first, in order, so the\n    // other variants' contexts can step around their names and their\n    // children's (`nonObjectVariantContexts`).\n    const objectVariantNames = new Map<SchemaObject, string>();\n    for (const variant of inlineObjectVariants) {\n      const named = deriveOneOfVariantName(\n        variant,\n        contextName,\n        inlineModels,\n        inlineObjectVariants,\n        contentNamed,\n        Boolean(op?.operationId),\n      );\n      const variantName = named.name;\n      if (named.fromContent) contentNamed.push(variantName);\n      objectVariantNames.set(variant, variantName);\n      const source = branch ?? variant;\n      const requiredSet = new Set(source.required ?? []);\n      const siblings = collectProperties(source);\n      const fields: Field[] = [];\n      for (const [fieldName, fieldSchema] of Object.entries(source.properties ?? {})) {\n        if (!fieldSchema) continue;\n        fields.push(buildFieldFromSchema(fieldName, fieldSchema, variantName, requiredSet, componentSchemas, siblings));\n      }\n      inlineModels.push({\n        name: variantName,\n        description: source.description,\n        ...externalDocsEntry(source.externalDocs),\n        fields,\n        ...deprecatedEntry(source),\n        ...constraintsEntry(source),\n        ...schemaExtensionsEntry(source),\n      });\n      extractInlineModelsFromProperties(source, inlineModels, variantName, componentSchemas);\n    }\n    // Every other variant that mints a name — an array or map, a nested\n    // union, a nullable wrapper around an object, an `allOf`, an inline enum\n    // — is typed under the context `nonObjectVariantContexts` gives it, apart\n    // from the object variants' names, and materialized by the field\n    // extractor under that context, so the body never references a model the\n    // parser did not create: the variants of a union nested under the body's\n    // second variant are `CreateThingRequestVariant2`,\n    // `BCreateThingRequestVariant2`, never `CreateThingRequest` again.\n    const variantContexts = nonObjectVariantContexts(\n      contextName,\n      schema.oneOf,\n      undefined,\n      undefined,\n      objectVariantNames,\n    );\n    for (const [variant, { context, reserved }] of variantContexts) {\n      extractInlineModelsFromProperties(\n        { properties: { [context]: unwrapNullableField(variant) } },\n        inlineModels,\n        undefined,\n        componentSchemas,\n        undefined,\n        reserved,\n      );\n    }\n\n    for (const variant of schema.oneOf) {\n      if (variant.$ref) {\n        const ref = schemaToTypeRef(variant, contextName);\n        variants.push(ref);\n      } else if (variant.type === 'null') {\n        // skip null variant in union, handle separately\n      } else {\n        const variantName = objectVariantNames.get(variant);\n        const entry = variantContexts.get(variant);\n        variants.push(\n          variantName !== undefined\n            ? { kind: 'model', name: variantName }\n            : entry\n              ? schemaToTypeRef(variant, entry.context, undefined, undefined, entry.reserved)\n              : schemaToTypeRef(variant, contextName),\n        );\n      }\n    }\n\n    const hasNull = schema.oneOf.some(\n      (v: SchemaObject) => v.type === 'null' || (Array.isArray(v.type) && v.type.includes('null')),\n    );\n    const union: TypeRef = {\n      kind: 'union',\n      variants,\n      ...(schema.discriminator\n        ? {\n            discriminator: { property: schema.discriminator.propertyName, mapping: schema.discriminator.mapping ?? {} },\n          }\n        : {}),\n    };\n    return hasNull ? ({ kind: 'nullable', inner: union } as TypeRef) : union;\n  }\n\n  // Anything else is typed by `schemaToTypeRef` (a primitive, an `anyOf`, an\n  // array, a map, a nullable object, a nullable wrapper around an array, a\n  // `$ref` or a primitive, …). Such a TypeRef can still reach inline models\n  // — the inline object variants of an `anyOf`, an array's inline items or\n  // the variants of an `items.oneOf`, a map's inline values, and whatever is\n  // nested under any of them, a union under a variant included — so\n  // materialize them the way an inline response does: as a property of this\n  // name under no parent, which names every nested model exactly as the\n  // TypeRef references it.\n  extractInlineModelsFromProperties(\n    { properties: { [contextName]: schema } },\n    inlineModels,\n    undefined,\n    componentSchemas,\n  );\n  return schemaToTypeRef(schema, contextName);\n}\n\n/**\n * Fold a discriminated-union request body into the equivalent single object so\n * its fields can be spread into method arguments instead of forcing callers to\n * construct an opaque union.\n *\n * The result is the union of every variant's properties: the discriminator is\n * collapsed to an enum of the pinned const values, and any field that isn't\n * present-and-required in *every* variant becomes optional (it varies by\n * branch, so it can't be unconditionally required). The discriminator itself is\n * always required. This mirrors what a spec author would write by hand to model\n * the same shape as a flat object.\n *\n * Returns null — leaving the union intact — unless the body is a clean\n * inline-object discriminated union: a variant that is a `$ref`, a non-object,\n * or that doesn't pin the discriminator to a string const can't be safely\n * merged. Gating on an *explicit* `discriminator` keeps undiscriminated `oneOf`\n * bodies untouched.\n */\nfunction flattenDiscriminatedUnionBody(schema: SchemaObject): SchemaObject | null {\n  const discProp = schema.discriminator?.propertyName;\n  if (!discProp || !Array.isArray(schema.oneOf) || schema.oneOf.length === 0) return null;\n\n  const variants = schema.oneOf as SchemaObject[];\n  const discValues: string[] = [];\n  let discPropSchema: SchemaObject | undefined;\n\n  for (const variant of variants) {\n    // Every variant must be an inline object that pins the discriminator to a\n    // string const (or single-value enum); anything else can't be merged.\n    if (variant.$ref || !variant.properties || !(variant.type === 'object' || variant.type === undefined)) {\n      return null;\n    }\n    const dp = variant.properties[discProp] as SchemaObject | undefined;\n    const constVal =\n      typeof dp?.const === 'string'\n        ? dp.const\n        : Array.isArray(dp?.enum) && dp.enum.length === 1 && typeof dp.enum[0] === 'string'\n          ? dp.enum[0]\n          : undefined;\n    if (constVal === undefined) return null;\n    if (!discValues.includes(constVal)) discValues.push(constVal);\n    if (!discPropSchema) discPropSchema = dp;\n  }\n\n  const variantCount = variants.length;\n  // Every declaration each property receives, in variant order; the first\n  // types the field, and the extensions are the ones every declaration\n  // agrees on (`agreedExtensions`, the one rule for a property several\n  // declarations give — workos/oagen#369 review: the discriminator was\n  // rebuilt from `type`, `enum` and `description` alone, and a shared field\n  // took the first variant's keys as written).\n  const declarations = new Map<string, SchemaObject[]>([[discProp, []]]);\n  const requiredCounts: Record<string, number> = {};\n\n  for (const variant of variants) {\n    const required = new Set(variant.required ?? []);\n    for (const [name, propSchema] of Object.entries(variant.properties!)) {\n      if (!propSchema) continue;\n      let declared = declarations.get(name);\n      if (!declared) declarations.set(name, (declared = []));\n      declared.push(propSchema as SchemaObject);\n      if (name !== discProp && required.has(name)) requiredCounts[name] = (requiredCounts[name] ?? 0) + 1;\n    }\n  }\n  const order = [...declarations.keys()]; // discriminator leads the merged object\n\n  const properties: Record<string, SchemaObject> = {};\n  for (const name of order) {\n    const declared = declarations.get(name)!;\n    properties[name] =\n      name === discProp\n        ? // The discriminator collapses to an enum of the pinned values,\n          // documented by the first variant's and carrying the agreed keys.\n          {\n            type: 'string',\n            enum: discValues,\n            ...(discPropSchema?.description ? { description: discPropSchema.description } : {}),\n            ...agreedExtensions(declared),\n          }\n        : withAgreedExtensions(declared[0]!, agreedExtensions(declared));\n  }\n\n  // Required only when required in every variant; the discriminator is always\n  // required.\n  const requiredFields = order.filter((name) => name === discProp || requiredCounts[name] === variantCount);\n\n  return {\n    type: 'object',\n    properties,\n    required: requiredFields,\n    ...(schema.description ? { description: schema.description } : {}),\n    // The wrapper's deprecation is the body's; a variant's is not carried,\n    // since its fields are merged away into the one body model.\n    ...deprecatedEntry(schema),\n    // The wrapper's link is the body's, like its description.\n    ...externalDocsEntry(schema.externalDocs),\n    // The wrapper's own keywords bind every branch, so they ride along; the\n    // variants' keywords are alternatives and are not carried.\n    ...extractConstraints(schema),\n    // The wrapper's own extensions are the body's, like its link; a\n    // variant's are not carried, since its fields merge into the one model.\n    ...extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n  };\n}\n\n/**\n * Derive a unique variant name for a request-body `oneOf` inline model.\n *\n * A variant with a string-const property is named after it\n * (`RadarEmailChallengeCodeSessionAuthenticateRequest`). Any other variant is\n * named from its content by the same rule every inline union variant follows\n * (`nameInlineVariant`): the first const-less variant keeps the body's name\n * (or its title, when every inline variant of the union is titled), and each\n * later one takes its title, a distinguishing property\n * (`CreateThingRequestWithB`) or, when its property set repeats an earlier\n * variant's, the position counter (`CreateThingRequest2`). `siblings` are the\n * union's inline object variants and `contentNamed` the names its const-less\n * variants have taken so far; `fromContent` tells the caller to record this\n * one there. A clash with a model minted elsewhere still bumps the counter:\n * on the base for a content-named variant (`CreateThingRequest2`), on the\n * const-derived name for a const-named one (`FooCreateThingRequest2`) — so a\n * variant titled `Foo` and a later one pinning `kind: foo` in the same body\n * never share a model.\n *\n * `fromOperationId` says where `baseName` came from. An operationId-derived\n * base is already in cleanSchemaName form and its variants go through\n * resolveSchemaName, so they follow the same project-level naming policy as\n * component schemas. A path-derived base is used verbatim: it is deliberately\n * not cleaned (see derivePathModelBaseName) and resolvePathModelBaseNames\n * reserves names by that exact prefix, so cleaning a variant here would let it\n * slip past the reservation — `NotesPostRequest` became `NotePostRequest` and\n * collided with a component of that name.\n */\nfunction deriveOneOfVariantName(\n  variant: SchemaObject,\n  baseName: string,\n  existingModels: Model[],\n  siblings: readonly SchemaObject[],\n  contentNamed: readonly string[],\n  fromOperationId: boolean,\n): { name: string; fromContent: boolean } {\n  const finalize = (name: string): string => (fromOperationId ? resolveSchemaName(name) : name);\n  const existingNames = new Set(existingModels.map((m) => m.name));\n  // `name`, or `<stem><n>` counting from 2 while a model of that name exists.\n  const unique = (name: string, stem: string): string => {\n    let candidate = name;\n    for (let suffix = 2; existingNames.has(candidate); suffix++) candidate = `${stem}${suffix}`;\n    return candidate;\n  };\n  // Try to use a distinguishing property (e.g., \"grant_type\" field's const/enum value)\n  if (variant.properties) {\n    for (const [, propSchema] of Object.entries(variant.properties)) {\n      if (propSchema?.const && typeof propSchema.const === 'string') {\n        const derivedName = finalize(toPascalCase(propSchema.const) + baseName.replace(/Request$/, '') + 'Request');\n        return { name: unique(derivedName, derivedName), fromContent: false };\n      }\n    }\n  }\n  // Finalize before naming so every candidate stays in the same namespace as\n  // the rest of the IR.\n  const finalBaseName = finalize(baseName);\n  const name = unique(nameInlineVariant(variant, siblings, finalBaseName, contentNamed, null), finalBaseName);\n  return { name, fromContent: true };\n}\n\n/** Human-readable label for an operation in diagnostics: its operationId, else `METHOD /path`. */\nfunction operationLabel(op: OperationObject | undefined, path: string, method: HttpMethod): string {\n  return op?.operationId ?? `${method.toUpperCase()} ${path}`;\n}\n\n/**\n * The servers an operation carries as `Operation.servers`: its own `servers`,\n * else its Path Item's (OpenAPI precedence: the operation overrides the Path\n * Item, which overrides the document), and only when that list differs from\n * the document's by `serverListsEqual`. `undefined` means the operation\n * inherits `ApiSpec.servers` — nothing usable is declared at either level\n * (`servers: []` and all-unusable entries included, since `extractServerList`\n * already reads both as undeclared), or the winning list restates the\n * document's — a restatement whose URLs differ only in scheme or host case,\n * a default port or a `/` after a bare authority included, since\n * `serverListsEqual` compares URLs through `normalizeServerUrl`. Precedence\n * is applied before the comparison, so an operation that restates the\n * document's servers under a Path Item that diverges inherits, not the Path\n * Item's.\n *\n * OpenAPI's default server is one thing however it is spelled (#291): a list\n * that means it — no servers, `servers: []`, or nothing but `/`, by\n * `isDefaultServerList`, description and variables aside (the default server\n * has neither, and `/` references no variable, so one declared on it changes\n * nothing — #292) — under a document whose list means it too is inherited as\n * well. So an operation or Path Item that writes `/` out under a document\n * that declares nothing inherits, the entry's description and variables\n * included. Any other list is compared\n * entry for entry as written, `/` entries included, because position decides\n * the default host: `/` under a document that names a host is kept, a named\n * host under a document that writes `/` out is kept, and a named host alone\n * under a document that lists `/` before that host is kept.\n */\nfunction operationServers(\n  own: ServerEntry[] | undefined,\n  pathLevel: ServerEntry[] | undefined,\n  documentServers: ServerEntry[] | undefined,\n): ServerEntry[] | undefined {\n  const effective = own ?? pathLevel;\n  if (!effective) return undefined;\n  if (serverListsEqual(effective, documentServers ?? [])) return undefined;\n  return isDefaultServerList(effective) && isDefaultServerList(documentServers) ? undefined : effective;\n}\n\n/**\n * The spec-wide registry of inline model shapes (see `InlineModelRegistry`):\n * the component models and the inline models their fields mint, every inline\n * model the operations mint for request bodies and primary responses, the\n * envelope companions, and each deferred model materialized so far. The value\n * carries the model's shape fingerprint, so a schema whose shape matches can\n * share the name, and the operation that minted it (none for a component or\n * a shared envelope companion), so a collision inside one operation can be\n * told apart from one across operations.\n */\ntype ModelShapeRegistry = InlineModelRegistry;\n\n/**\n * A header, secondary-body, fallback-body or error-body schema whose inline\n * models are named only once every primary model of every operation is known\n * (`resolveDeferredInlineTypes`), which then fills in `target.type`. Until\n * then the target carries a placeholder.\n */\ninterface DeferredInlineType {\n  kind: 'header' | 'content' | 'request' | 'fallback' | 'error' | 'param';\n  schema: SchemaObject;\n  /**\n   * The bare name the models derive from: the header name; a success or\n   * fallback entry's secondary body, the stem + media type + `Response`; a\n   * secondary request body's `<Op><MediaType>Request`; a fallback body's\n   * `<Op><Label>Response` (`default`, `1XX`–`3XX`); an error body's\n   * `<Op>Error<code>` — the status code or the `4XX`/`5XX` range key, then\n   * the media type for a secondary body (`<Op>Error<code><MediaType>`); a\n   * parameter's name; or `<Component>Response` for a fallback or error body\n   * a `components/responses` entry declares.\n   */\n  name: string;\n  /**\n   * Set for a site a `components/responses` entry declares — its fallback or\n   * error body (`<Component>Response`), an inline body under another media\n   * type (`<Component><MediaType>Response`), an object-shaped header\n   * (`<Component><Header>`) — named after the component wherever the\n   * component is returned: a 404 of one operation, the `default` or a range\n   * of another. Every such site is a sibling of every other that derives the\n   * same name, whatever its kind, and on a clash steps by number alike\n   * (`ProblemResponse2`, `CardXMeta2`, `CardApplicationYamlResponse2`), never\n   * by the operation or status code that mounted the component, so all\n   * settle on one name that depends on the component alone.\n   */\n  componentSite?: boolean;\n  /**\n   * What tells this site from another of the same name within one operation:\n   * a status code, the key of a `4XX`/`5XX` range (`4XX`), the label of a\n   * `default` or `1XX`–`3XX` response (`Default`, `Success`), or a\n   * parameter's location (`query`); a request body has none.\n   */\n  statusCode?: number | string;\n  /** Qualifies a name taken across operations (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /**\n   * Qualifies a header's names: the service for a header of an inline\n   * response (`Documents` + `X-Meta` → `DocumentsXMeta`), the component's\n   * stem for one of a response shared through `components/responses`\n   * (`Card` + `X-Meta` → `CardXMeta`); a body has none.\n   */\n  parentName?: string;\n  componentSchemas?: Record<string, SchemaObject>;\n  /**\n   * Everything the resolved type is written to: the header or content entry,\n   * and for a fallback or error body both the response entry and the content\n   * entry of the media type it was read from, which share one TypeRef as a\n   * success entry's do.\n   */\n  targets: Array<{ type?: TypeRef }>;\n}\n\n/** What response header and body typing needs from the operation and the spec. */\ninterface ResponseTypingContext {\n  componentHeaders?: Record<string, Record<string, unknown>>;\n  /** Lets inline models resolve `$ref` siblings and augmentations the way fields do. */\n  componentSchemas?: Record<string, SchemaObject>;\n  /** `components/responses`, for a response written as a Reference Object. */\n  componentResponses?: Record<string, Record<string, unknown>>;\n  /**\n   * Whether a `description` written beside a response or header `$ref`\n   * overrides the component's (OAS 3.1) or is ignored (OAS 3.0); see\n   * `followReference`. Absent, it overrides.\n   */\n  refSiblingDescriptions?: SiblingDocs;\n  /**\n   * The model name each component response's inline body is shared under\n   * (`resolveComponentResponseModelNames`). Absent, every component keeps\n   * `componentResponseModelName`.\n   */\n  componentResponseModelNames?: ReadonlyMap<string, string>;\n  /**\n   * Qualifies the header model and enum names of an inline response:\n   * `Documents` + `X-Meta` → `DocumentsXMeta`. A response shared through\n   * `components/responses` qualifies its headers by the component instead\n   * (`responseModelSite`).\n   */\n  serviceName?: string;\n  /** Qualifies a name taken across operations (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /** Collects every schema whose models are named after the operations loop. */\n  deferred: DeferredInlineType[];\n  /**\n   * The spec-wide registry of model shapes the operations fill as they are\n   * read (see `extractOperations`); with it, the primary body's array items\n   * are settled against every name it holds (`typeInlineItems`). Absent for\n   * a dry run that only reads the names a body would mint.\n   */\n  registry?: ModelShapeRegistry;\n}\n\n/**\n * Name and materialize every deferred header, secondary request-body,\n * secondary response-body, fallback-body, error-body and parameter schema,\n * now that every primary model is known. The registry comes filled from\n * `extractOperations`: the component models first (with the inline models\n * their fields mint), each seeded with the model itself so it shares its\n * name with every shape it admits (`ownerShares`), then every inline model\n * the operations minted — request bodies, primary response bodies with\n * their nested objects, union variants and settled array items, envelope\n * companions — shared on an identical shape only, so no deferred schema\n * can take one of their names for a shape the owner does not share,\n * whichever operation minted it; each resolved schema's own models join it\n * in turn, in document order (path order, then an operation's secondary\n * request bodies in content order, then the response keys as written; a\n * response's headers before its error body and its secondary bodies, a\n * fallback's body before its headers), so the first owner of a name keeps\n * it. Every enum name decided before this pass, component or minted, is\n * held too, as a name no model may take (`reserveEnumNames`): a deferred\n * schema that derives one steps to its next candidate, so a component enum\n * `ReplaceWidgetTextCsvRequest` sends the `text/csv` body's model to\n * `ReplaceWidgetTextCsvRequest2`. The sites that derive from one bare name\n * — one kind, parent and name: the same header on several status codes or\n * operations, one media type's body on several status codes, a component\n * response's header or secondary body from every operation that returns it;\n * or one component response's body, whether the site is an error or a\n * fallback entry (`componentSite`) — share a record of the stems they settled on and\n * the renames made under them, so a later one shares an identical shape\n * under whichever name the earlier took (`materializeInlineSchema`).\n *\n * Two precedences decide a name a model and an enum both derive. An enum\n * typed as an operation is built — one a parameter, a request body, a\n * success body, a pagination field carries — is in the registry before this\n * pass and keeps its name wherever the document declares it: a `status`\n * query enum on a later operation sends an earlier operation's `status`\n * parameter object to `PetsListPetsStatus`, and the same operation's to\n * `PetsQueryStatus`. Among the sites named here — response headers, error\n * bodies, secondary and fallback bodies, parameter models — document order\n * decides: each site registers the enums it types (a body that is itself an\n * enum, an enum nested in a model it minted) as it is resolved, so the\n * earlier site keeps the name and a later one that derives it steps (an\n * `X-Mode` header parameter object after an earlier operation's `X-Mode`\n * response-header enum is `PetsGetPetXMode`) — except that the enum a body\n * itself is (an error, fallback or secondary body that is an inline enum,\n * or an array of one) is reserved before any of these sites is named\n * (`deferredEnumName`), so `getPet`'s object 404 is `GetPetError404Body`\n * whether `get-pet`'s enum 404 comes before or after it. So the IR never\n * declares a model and an enum under one name, and the model is always\n * the one that steps. Returns the models materialized, having set each\n * target's `type`.\n */\nfunction resolveDeferredInlineTypes(\n  deferred: readonly DeferredInlineType[],\n  registry: ModelShapeRegistry,\n): { models: Model[]; bundles: InlineModelBundle[] } {\n  const models: Model[] = [];\n  const bundles: InlineModelBundle[] = [];\n  const siblingsByBareName = new Map<string, SiblingSites>();\n  for (const item of deferred) {\n    // A component response's site is one site wherever the component is\n    // returned, so its record is keyed by the name the component gives it\n    // alone (its body's, or a header's under the component's stem), not by\n    // whether the site is an error or a fallback entry.\n    const bareName = item.componentSite\n      ? `component\\u0000${item.parentName ?? ''}\\u0000${item.name}`\n      : `${item.kind}\\u0000${item.parentName ?? ''}\\u0000${item.name}`;\n    let siblings = siblingsByBareName.get(bareName);\n    if (!siblings) siblingsByBareName.set(bareName, (siblings = createSiblingSites()));\n    const minted = models.length;\n    const type = materializeDeferredType(item, registry, models, siblings);\n    // An enum this site typed — a body that is itself an enum, one nested in\n    // a model it minted — owns its name from here on, as the site's models do.\n    reserveEnumNames(\n      registry,\n      [type, ...models.slice(minted).flatMap(collectModelTypeRefs)].flatMap(collectEnumRefs),\n      item.operationQualifier,\n    );\n    for (const target of item.targets) target.type = type;\n    // The one TypeRef every target shares is the site's root; the models\n    // minted for it are the site's own (a shape that shared another site's\n    // model minted nothing here, see `attachSharedRefs`).\n    bundles.push({\n      qualifier: item.operationQualifier,\n      roots: [type],\n      models: models.slice(minted),\n      ...(isSentSite(item) ? { sent: true } : {}),\n    });\n  }\n  return { models, bundles };\n}\n\n/**\n * Give each reference a site wrote by sharing another site's model to that\n * site. A shape identical to a name's owner takes the name and mints\n * nothing — a deferred header or body matching a primary body's model or a\n * companion's, an array body's or list envelope's items matching a\n * component field's model or an earlier operation's (`typeInlineItems`\n * through `materializeInlineSchema`) — so its reference is not among the\n * owner's roots, and a merge pass that renames the owner (a deprecated copy\n * named like a live one, `settleSharedNames`) would leave the\n * `default` response, header or array on the old name, which the live copy\n * then takes. The first site to mint a name owns it, as the registry\n * decided; the references every other site's roots and its own models'\n * fields make to that name are added to the owner's roots, so they are\n * repointed with the owner's own. A reference to a name the site itself\n * minted is the site's own, not shared, and is left to its own bundle — two\n * operations minting one name with different shapes are the merge's\n * business, and attaching one to the other would drag a live copy's\n * references along with a renamed deprecated one; a component is never\n * renamed, so a reference to one is left alone. Idempotent: run over the\n * operations' bundles once they are complete (`extractOperations`) and again\n * once the components' field bundles exist (`parseSpec`) — there a field's\n * bundle stands for the object the component pass minted for the field\n * (`fieldInlineModelBundles`), so a header or fallback body that shared that\n * object joins the field's site and follows its rename.\n */\nexport function attachSharedRefs(bundles: readonly InlineModelBundle[], componentNames: ReadonlySet<string>): void {\n  const siteOf = new Map<string, InlineModelBundle>();\n  for (const bundle of bundles) {\n    for (const model of bundle.models) if (!siteOf.has(model.name)) siteOf.set(model.name, bundle);\n  }\n  for (const bundle of bundles) {\n    const own = new Set(bundle.models.map((model) => model.name));\n    const refs = [...bundle.roots, ...bundle.models.flatMap((model) => collectModelTypeRefs(model))];\n    for (const ref of refs) {\n      for (const name of collectModelRefs(ref)) {\n        if (componentNames.has(name) || own.has(name)) continue;\n        const site = siteOf.get(name);\n        if (site && site !== bundle && !site.roots.includes(ref)) site.roots.push(ref);\n      }\n    }\n  }\n}\n\n/**\n * Type a deferred schema and materialize the inline models it names, under a\n * property name that does not collide with a different shape anywhere in the\n * spec — through `materializeInlineSchema`, the one retry loop every such\n * schema goes through.\n *\n * A header model is named from the service and header name alone, so an\n * inline `X-Meta` on a `Documents` operation is `DocumentsXMeta`; a secondary\n * body from the operation's response stem and media type,\n * `RenderPetCardTextHtmlResponse`; either, on a response shared through\n * `components/responses`, from the component's stem instead (`CardXMeta`,\n * `CardApplicationYamlResponse`; see `responseModelSite`); a `default` or\n * `1XX`–`3XX` body from the stem and the response's label,\n * `ListPetsDefaultResponse`; an error body from the stem and its status code\n * or `4XX`/`5XX` range key, `GetPetError404`, `GetPetError4Xx`\n * (`deriveErrorModelName`), and a secondary media type's error body from\n * that name and the media type, `GetPetError404ApplicationYaml`; a\n * parameter from the service and parameter name, `PetsFilter`. Any of them\n * is a name a component schema, a model nested in one (`GetPet.error404` owns\n * `GetPetError404`), a primary body, the same header on a 429 or another\n * operation may already own with a different shape, or an enum — a\n * component's, or one a parameter or field lifts — may own outright\n * (`reserveEnumNames`). Left alone, the later\n * merge keeps one definition for the name and every other reference silently\n * gets the wrong fields (a request body using the component would even change\n * type without any emitter reading headers).\n *\n * The first owner of a name keeps it (see `resolveDeferredInlineTypes`), and\n * a later schema with a different shape — at any depth, a nested object that\n * differs counts — is re-derived under the first free candidate of its kind\n * (`deferredNamingStem`):\n *\n *   header    1. the bare name                `DocumentsXMeta`\n *             2. when the name is taken inside this operation, the status\n *                code (`DocumentsXMeta429`); when taken by a component or\n *                another operation, the operation (`DocumentsCreateDocumentXMeta`)\n *             3. the other of those two\n *             4. operation and status code    `DocumentsCreateDocumentXMeta429`\n *             5. a numeric suffix             `DocumentsXMeta2`, `DocumentsXMeta3`, …\n *   content   (a success or fallback entry's secondary body)\n *             1. the bare name                `RenderPetCardTextHtmlResponse`\n *             2. the status code              `RenderPetCardTextHtmlResponse201`\n *             3. a numeric suffix             `…Response2`, `…Response3`, …\n *   request   1. the bare name                `ReplaceWidgetTextCsvRequest`\n *             2. a numeric suffix             `ReplaceWidgetTextCsvRequest2`, `…3`, …\n *   fallback  (a `default` or `1XX`–`3XX` body)\n *             1. the bare name                `ListPetsDefaultResponse`\n *             2. a numeric suffix             `ListPetsDefaultResponse2`, `…3`, …\n *   error     (an error entry's JSON body, its secondary bodies, and a\n *             `4XX`/`5XX` range's bodies alike)\n *             1. the bare name                `GetPetError404`, `GetPetError404ApplicationYaml`, `GetPetError4Xx`\n *             2. a `Body` suffix              `GetPetError404Body`\n *             3. a numbered `Body` suffix     `GetPetError404Body2`, `…Body3`, …\n *   a site a `components/responses` entry declares (`componentSite`) — its\n *   fallback or error body, a secondary body, a header — whichever kind it is:\n *             1. the bare name                `ProblemResponse`, `CardXMeta`, `CardApplicationYamlResponse`\n *             2. a numeric suffix             `ProblemResponse2`, `CardXMeta2`, `CardApplicationYamlResponse2`, …\n *\n * Between the bare name and the kind's own qualifiers come the stems the\n * earlier sites of the same kind, parent and bare name settled on\n * (`siblings`, kept by `resolveDeferredInlineTypes`): the `X-Meta` header of\n * a 429 tries the `DocumentsXMeta200` its 200 took before `DocumentsXMeta429`,\n * and the `application/vnd.pet+json` body of a 201 tries the `…Response200`\n * its 200 took before `…Response201`, so an identical shape shares the\n * earlier site's model under whichever name that site settled on, and a\n * different shape steps past it to its own qualifier. A fallback body named\n * from the operation carries the response's label in its bare name and an\n * error body named from it its status code, so within an operation each has\n * a bare name of its own and no sibling to try. A component response's body\n * carries the component's name wherever the component is returned, so the\n * 404 of one operation and the `default` of another are siblings, and an\n * identical shape — the component's own, every time — shares the first\n * site's model under whichever name it settled on; its headers and\n * secondary bodies are siblings across operations the same way, under the\n * component's stem.\n *\n * Both the type and the models come from the same property name, so nested\n * models (`DocumentsXMeta429Origin`) line up by construction. A shape the\n * name's current owner shares — identical to an operation's model, or one a\n * component admits (`ownerShares`) — takes the name and materializes nothing\n * new, which is how a header reuses a component model. A\n * title-mapped union variant (`Circle`) is named from its title whatever the\n * property name, so `materializeInlineSchema` reserves every taken name and\n * such a variant falls back to its context-qualified name\n * (`CircleDocumentsXMeta`, see `nameInlineVariants`). A clash neither a\n * candidate nor a reservation can clear — a titled variant nested below the\n * top level — is not looped on: the clashing models are renamed under the\n * schema's root (`RenderPetCardTextHtmlResponseCircle`) with every reference\n * rewritten, whatever the kind.\n *\n * Treating the schema as a one-property object reuses the field-level\n * extractor, whose names come from the same `qualifyInlineModelName(name,\n * parent)` rule `schemaToTypeRef` applies — the trick the inline request-body\n * path uses.\n */\nfunction materializeDeferredType(\n  item: DeferredInlineType,\n  registry: ModelShapeRegistry,\n  models: Model[],\n  siblings: SiblingSites,\n): TypeRef {\n  return materializeInlineSchema(item.schema, {\n    stem: deferredNamingStem(item),\n    siblings,\n    parentName: item.parentName,\n    componentSchemas: item.componentSchemas,\n    registry,\n    operation: item.operationQualifier,\n    sent: isSentSite(item),\n    models,\n  });\n}\n\n/** Whether a deferred schema is one the SDK sends — a secondary request body or a parameter — rather than receives. */\nfunction isSentSite(item: DeferredInlineType): boolean {\n  return item.kind === 'request' || item.kind === 'param';\n}\n\n/**\n * The enum name a deferred body typed as an inline enum — an error, fallback\n * or secondary body whose schema is an `enum:` list, or an array of one — is\n * lifted under when its site is resolved: its first candidate\n * (`deferredNamingStem`) as `schemaToTypeRef` names an enum under it, the\n * site's parent qualifying it as a header's does (`inlineEnumSchemaName`);\n * undefined for every other shape, which mints models or nothing.\n */\nfunction deferredEnumName(item: DeferredInlineType): string | undefined {\n  return inlineEnumSchemaName(item.schema, deferredNamingStem(item)(0, []), item.parentName);\n}\n\n/** The candidate property names of a deferred schema, by kind (see `materializeDeferredType`). */\nfunction deferredNamingStem(item: DeferredInlineType): (index: number, firstClashOwners: InlineModelOwner[]) => string {\n  const { name, statusCode = '', operationQualifier } = item;\n  const byStatus = `${name}${statusCode}`;\n  const numbered = (index: number): string => `${name}${index + 2}`;\n  const byNumber = (index: number): string => (index === 0 ? name : numbered(index - 1));\n  // A site a component response declares — its body, a secondary body, a\n  // header — steps the same way from every operation, at a 404, at `default`\n  // and in a range: by number, as the pre-pass that named the body steps\n  // (`resolveComponentResponseModelNames`), never by the operation or status\n  // code below, which belong to operation-owned sites; so every site that\n  // returns the component reaches the same name (workos/oagen#302).\n  if (item.componentSite) return byNumber;\n  switch (item.kind) {\n    case 'header': {\n      // Decide the preference between candidates 2 and 3 from the bare\n      // name's owners: a clash within this operation reads best by status\n      // code, one with a component, a primary body or another operation by\n      // operation name. Joined with `_`, as a parameter's are, since the\n      // bare name is the lower-cased header name (`ListDocuments_x-meta` →\n      // `ListDocumentsXMeta`, not `ListDocumentsxMeta`).\n      const byOperationName = `${operationQualifier}_${name}`;\n      const byOperationAndStatus = `${operationQualifier}_${name}${statusCode}`;\n      return (index, firstClashOwners) => {\n        const withinOperation = firstClashOwners.every((owner) => owner.operation === operationQualifier);\n        const candidates = withinOperation\n          ? [name, byStatus, byOperationName, byOperationAndStatus]\n          : [name, byOperationName, byStatus, byOperationAndStatus];\n        return index < candidates.length ? candidates[index] : numbered(index - candidates.length);\n      };\n    }\n    case 'content':\n      return (index) => (index === 0 ? name : index === 1 ? byStatus : numbered(index - 2));\n    case 'request':\n    case 'fallback':\n      return byNumber;\n    case 'error':\n      return (index) => (index === 0 ? name : index === 1 ? `${name}Body` : `${name}Body${index}`);\n    case 'param': {\n      // Named like a header, with the location where a header has its\n      // status code: a clash within this operation (one name in two\n      // locations) reads best by location, one with a component, a primary\n      // body or another operation by operation name. Joined with `_` so a\n      // lower-case parameter name still starts a word (`ListPets_filter` →\n      // `ListPetsFilter`).\n      const byLocation = `${statusCode}_${name}`;\n      const byOperationName = `${operationQualifier}_${name}`;\n      const byOperationAndLocation = `${operationQualifier}_${statusCode}_${name}`;\n      return (index, firstClashOwners) => {\n        const withinOperation = firstClashOwners.every((owner) => owner.operation === operationQualifier);\n        const candidates = withinOperation\n          ? [name, byLocation, byOperationName, byOperationAndLocation]\n          : [name, byOperationName, byLocation, byOperationAndLocation];\n        return index < candidates.length ? candidates[index] : numbered(index - candidates.length);\n      };\n    }\n  }\n}\n\n/**\n * Defer the typing of every parameter of one location whose inline schema\n * mints a model — an object (`style: deepObject`), an array or map of\n * objects, a union with an inline object variant, a nullable wrapper around\n * one, at any depth — so the model is created, as a response header's is,\n * once every primary model is known (`resolveDeferredInlineTypes`), under a\n * name nothing else owns: `<Service><Param>` (`PetsFilter`), else the\n * location-, operation- or number-qualified candidates `deferredNamingStem`\n * lists; a name an enum has or will have — a component enum's, or the name\n * another parameter's or a field's inline enum is lifted under (`PetsKind`)\n * — is reserved in the registry, so the model steps to the\n * operation-qualified name (`PetsSearchPetsKind`). Called after the\n * operation's responses have been read, so a parameter's site follows the\n * response headers' in the registry: a response header the operation\n * already typed keeps its name (`PetsXMeta`), and a header parameter of the\n * same name takes the location-qualified one (`PetsHeaderXMeta`).\n * `extractParams` typed the parameter as the property of its name under the\n * service, and the trial extraction here reads the same synthetic property,\n * so the deferred site's first candidate is the name the parameter already\n * references and a parameter that mints no model — a primitive, a `$ref`,\n * an inline enum, an array of either — keeps the type it has and is not\n * deferred. `raw` and `typed` are the location's parameters in document\n * order, `typed[i]` built from `raw[i]` (`extractParams` maps the filtered\n * list one to one).\n */\nfunction deferParameterModels(\n  raw: readonly ParameterObject[],\n  typed: readonly Parameter[],\n  location: ParameterObject['in'],\n  ctx: ResponseTypingContext,\n): void {\n  const parentName = ctx.serviceName ? toPascalCase(ctx.serviceName) : undefined;\n  raw.forEach((param, index) => {\n    const target = typed[index];\n    // The schema `extractParams` typed the parameter from: `schema`, else the\n    // picked `content` entry's (`parameterTyping`).\n    const schema = parameterSchema(param);\n    if (!schema || !target) return;\n    // The name the models derive from is the one `extractParams` typed the\n    // parameter under — a header's lower-cased (`foldParameterName`) — so the\n    // reference and the model agree, and neither moves with the header's case.\n    const name = foldParameterName(location, param.name);\n    const trial: Model[] = [];\n    extractInlineModelsFromProperties({ properties: { [name]: schema } }, trial, parentName, ctx.componentSchemas);\n    if (trial.length === 0) return;\n    ctx.deferred.push({\n      kind: 'param',\n      schema,\n      name,\n      statusCode: location,\n      operationQualifier: ctx.operationQualifier,\n      parentName,\n      componentSchemas: ctx.componentSchemas,\n      targets: [target],\n    });\n  });\n}\n\n/**\n * Read a Response Object's `headers` map into IR response headers, resolving\n * `components/headers` refs. Returns `undefined` rather than `[]` when nothing\n * survives so callers can leave the `headers` key off entirely.\n *\n * An object-shaped header schema (directly, inside an array, or as a oneOf\n * variant) becomes a `ModelRef`, so the model it names must be materialized\n * — otherwise the ref would dangle with nothing to emit. That naming waits\n * for every primary model (`resolveDeferredInlineTypes`), so a header with a\n * schema is deferred and its `type` filled in then, qualified by\n * `site.headerParent`: the service for a header of an inline response\n * (`Notes` + `X-Meta` → `NotesXMeta`), the component's stem for one of a\n * response shared through `components/responses` (`Card` + `X-Meta` →\n * `CardXMeta`), as `responseModelSite` decides; the latter is a component\n * site (`componentSite`), so on a clash it steps by number (`CardXMeta2`)\n * rather than by the operation or status code.\n *\n * Header names are case-insensitive (RFC 9110 §5.1; OpenAPI says so of this\n * map), so two keys that differ in case alone (`X-Request-Id` beside\n * `x-request-id`) declare one header: the later declaration is kept, in the\n * earlier one's position, with a warning — the way an operation-level\n * parameter replaces a path-level one, except that the document gave these\n * two no precedence (#295).\n */\nfunction extractResponseHeaders(\n  headers: Record<string, RawHeaderObject> | undefined,\n  operationLabel: string,\n  // A status code, or the label of a fallback response (`Default`, `ClientError`).\n  statusCode: number | string,\n  ctx: ResponseTypingContext,\n  site: ResponseModelSite,\n): ResponseHeader[] | undefined {\n  if (!headers) return undefined;\n\n  const declarations = new Map<string, { name: string; raw: RawHeaderObject }>();\n  for (const [name, raw] of Object.entries(headers)) {\n    const folded = foldHeaderName(name);\n    const earlier = declarations.get(folded);\n    if (earlier) {\n      console.warn(\n        `[oagen] Warning: Response header \"${name}\" on ${operationLabel} ${statusCode} is also declared as \"${earlier.name}\"; header names are case-insensitive, so the later declaration is used.`,\n      );\n    }\n    declarations.set(folded, { name, raw });\n  }\n\n  const result: ResponseHeader[] = [];\n  for (const [folded, { name, raw }] of declarations) {\n    // OAS 3.x: a response header named `Content-Type` SHALL be ignored; the\n    // media type is already carried by the response's `content` map.\n    if (folded === 'content-type') continue;\n\n    const header = resolveHeaderRef(raw, ctx.componentHeaders, name, operationLabel, ctx.refSiblingDescriptions);\n    if (!header) continue;\n\n    // A Header Object declares `schema` or a single-entry `content` map; the\n    // schema that types the header is resolved as a parameter's is\n    // (`parameterTyping`): `schema`, else the picked `content` entry's. A map\n    // none of whose media types is read leaves the header a string, with a\n    // warning — once, here, as the header is typed.\n    const schema = parameterSchema(header);\n    warnUnreadParameterContent(header, `Response header \"${name}\" (${statusCode}) in ${operationLabel}`);\n    const entry: ResponseHeader = {\n      name,\n      type: { kind: 'primitive', type: 'string' },\n      required: header.required ?? false,\n      description: header.description,\n      deprecated: header.deprecated === true || undefined,\n      // The header schema's own link — a Header Object has none — read from\n      // whichever of `schema` and `content` types the header, as the type is.\n      ...externalDocsEntry(schema?.externalDocs),\n    };\n    if (schema) {\n      // Named from the lower-cased header name, as a header parameter's inline\n      // type is, so the model or enum a header mints keeps its name when the\n      // header's case changes; `entry.name` stays as written.\n      ctx.deferred.push({\n        kind: 'header',\n        schema,\n        name: folded,\n        statusCode,\n        operationQualifier: ctx.operationQualifier,\n        parentName: site.headerParent,\n        componentSchemas: ctx.componentSchemas,\n        targets: [entry],\n        ...(site.shared && { componentSite: true }),\n      });\n    }\n    result.push(entry);\n  }\n\n  return result.length > 0 ? result : undefined;\n}\n\n/**\n * Build the prefix (`NotesByIdPinPost`) that names both inline models — the\n * request body (`…Request`) and the response (`…Response`) — of an operation\n * that has no `operationId`, from the only thing that identifies it: its path\n * and method.\n *\n * Every non-parameter segment is PascalCased in order and every parameter\n * segment becomes `By` + PascalCase(param name); then the optional\n * disambiguator and the method are appended. The whole is normalized with\n * toPascalCase so it is a fixed point of that function: responses.ts re-cases\n * the response name in `deriveModelName`, and without this step `POST /a/b`\n * named its body `ABPostRequest` but its response `AbPostResponse`.\n *\n *   GET  /widgets                   → WidgetsGet\n *   POST /notes                     → NotesPost\n *   POST /notes/{id}/pin            → NotesByIdPinPost\n *   GET  /users/{user_id}/sessions  → UsersByUserIdSessionsGet\n *\n * This tells the common path shapes apart (list vs. item, sibling and nested\n * sub-resources) but is not unique by construction: `/foo-bar` and `/foo/bar`,\n * `/notes/by-id` and `/notes/{id}`, `/notes` and `/notes/`, and a custom\n * method beside its slash form, `/pets/{id}:adopt` and `/pets/{id}/adopt`\n * (pathSegments reads the first as `{id}` then `adopt`), all flatten to the\n * same words. `resolvePathModelBaseNames` detects such collisions: the path\n * spelled most plainly keeps the plain name and every other one gets a\n * `disambiguator` derived from its raw path.\n *\n * A single-segment path keeps the name the old first-segment rule produced.\n * The result is deliberately not passed through cleanSchemaName (the old\n * fallback wasn't either): the segments are the resource names as the API\n * spells them.\n */\nexport function derivePathModelBaseName(path: string, method: HttpMethod, disambiguator = ''): string {\n  const segments = pathSegments(path);\n  const parts = segments.map((segment) =>\n    segment.startsWith('{') ? 'By' + toPascalCase(segment.replace(/[{}]/g, '')) : toPascalCase(segment),\n  );\n  const resource = parts.length > 0 ? parts.join('') : 'Unknown';\n  // `_` separators guarantee a word boundary on each side of the disambiguator\n  // and the method, whatever the resource ends with; splitWords drops them.\n  return toPascalCase([resource, disambiguator, method].filter(Boolean).join('_'));\n}\n\n/** `derivePathModelBaseName` plus the `Request` / `Response` suffix. */\nexport function derivePathBasedName(\n  path: string,\n  method: HttpMethod,\n  suffix: 'Request' | 'Response',\n  disambiguator = '',\n): string {\n  return derivePathModelBaseName(path, method, disambiguator) + suffix;\n}\n\n/**\n * Decide the path-derived model prefix of every operation that has no\n * `operationId`, keyed by `${method} ${path}`.\n *\n * A prefix collides when two distinct raw paths with the same method flatten\n * to it (see derivePathModelBaseName), or when a reserved name starts with\n * it. The reserved names are every resolved component model name and, for\n * every operation with an `operationId`, its model stem\n * (operationIdModelBase). A prefix is the stem of several emitted names —\n * `…Request`, `…Response`, a list's `…Item`, nested inline models such as\n * `…ResponseOwner`, envelope companions such as `…ListMetadata` — so the\n * check is on the stem, not on an enumeration of suffixes: an unnamed\n * `GET /audit/events` must not overwrite `components/schemas/AuditEventsGetItem`\n * any more than an unnamed `POST /audit/events` may overwrite the models of\n * a `POST /legacy-audit` whose operationId is `auditEventsPost`. Reserved\n * names never change.\n *\n * This is deliberately a superset: a component named `AuditEventsGetter`, or\n * an operationId `auditEventsGetSummary`, also pushes `GET /audit/events`\n * onto a hashed name although no emitted name would coincide. Determinism\n * and never sharing a name wrongly matter more than the rare extra hash, and\n * the reservation is unconditional — an inline body is never merged into a\n * same-named component even when the shapes agree — so the rule stays\n * simple and order-free. Every name derived from a path-based prefix uses it\n * verbatim (body `oneOf` variants included; see deriveOneOfVariantName), and\n * as a second line of defence the check also runs on the cleaned spellings\n * of the prefix (see prefixSpellings), so `GET /notes` yields to a component\n * `NoteGetItem` although its own item model is `NotesGetItem`. Names that\n * embed the prefix behind a const value — a body `oneOf` variant pinning\n * `kind: email` is `EmailTagsPostRequest`, a nested variant\n * `<Const><Parent><Field>` — are checked too, with each const the operation\n * can mint prepended to every spelling (see collectOperationConstPrefixes);\n * the hash then lands inside those names as well (`EmailTags151Dd5PostRequest`).\n *\n * These names are types SDK users read and import, so a collision costs the\n * plain name only where it must. Within a group of paths that flatten to one\n * prefix, the path spelled most plainly (see pathDeviation: no trailing\n * slash, `{id}` rather than a literal `by-id`) is canonical and keeps the\n * plain prefix; every other path gets a six-character disambiguator, the\n * start of the SHA-1 of its raw path, inserted before the method\n * (`POST /foo-bar` next to `POST /foo/bar` → `FooBar546F12Post`). When two\n * paths tie for plainest, or the prefix is reserved, nobody is canonical and\n * every path in the group is disambiguated. The outcome depends only on the\n * document's paths, operationIds and component names, never on their order,\n * and a path that stops colliding returns to its plain name.\n */\nfunction resolvePathModelBaseNames(\n  paths: Record<string, PathItem>,\n  componentModels?: Model[],\n  componentRequestBodies?: Record<string, Record<string, unknown>>,\n  componentResponseNaming: ReadonlyMap<string, ComponentResponseNaming> = new Map(),\n): Map<string, string> {\n  const candidates: Array<{ key: string; path: string; method: HttpMethod; plain: string }> = [];\n  const rawPathsByPlainName = new Map<string, Set<string>>();\n  const constPrefixesByPlainName = new Map<string, Set<string>>();\n  const reservedNames = new Set<string>();\n\n  for (const model of componentModels ?? []) {\n    reservedNames.add(model.name);\n  }\n  // A shared response names its inline body after the component, not the\n  // operation (see componentResponseModelName), so its stem is reserved like\n  // an operationId's — and so is every name that body mints, the model and\n  // everything nested under it (`OwnerCardResponseAddressGetResponse` for an\n  // `address_get_response` object in `OwnerCard`): a path stem that merely\n  // extends the component's (`GET /owner/card/response/address` →\n  // `OwnerCardResponseAddressGet`) starts with none of the stems above, yet\n  // its `…Response` is exactly such a nested name, and the later merge would\n  // keep one shape for both. The names are the ones\n  // `resolveComponentResponseModelNames` read with the extractor the\n  // operation will use, under the same context name, so they agree by\n  // construction.\n  for (const [componentName, naming] of componentResponseNaming) {\n    reservedNames.add(componentResponseModelBase(componentName));\n    reservedNames.add(naming.name);\n    for (const name of naming.minted) reservedNames.add(name);\n  }\n\n  for (const [path, pathItem] of Object.entries(paths)) {\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op) continue;\n      if (op.operationId) {\n        reservedNames.add(operationIdModelBase(op.operationId));\n        continue;\n      }\n      const plain = derivePathModelBaseName(path, method);\n      candidates.push({ key: `${method} ${path}`, path, method, plain });\n      const rawPaths = rawPathsByPlainName.get(plain) ?? new Set<string>();\n      rawPaths.add(path);\n      rawPathsByPlainName.set(plain, rawPaths);\n      const constPrefixes = constPrefixesByPlainName.get(plain) ?? new Set<string>();\n      for (const prefix of collectOperationConstPrefixes(\n        op,\n        componentRequestBodies,\n        operationLabel(op, path, method),\n      )) {\n        constPrefixes.add(prefix);\n      }\n      constPrefixesByPlainName.set(plain, constPrefixes);\n    }\n  }\n\n  const reservedList = [...reservedNames];\n  const canonicalByPlainName = new Map<string, string | undefined>();\n  for (const [plain, rawPaths] of rawPathsByPlainName) {\n    // Every stem a name minted from this prefix can start with: the prefix in\n    // each of its cleaned spellings, and each const value the operation can\n    // prepend to it (`EmailTagsPostRequest` is `Email` + `TagsPost…`).\n    const spellings = prefixSpellings(plain);\n    const constPrefixes = ['', ...(constPrefixesByPlainName.get(plain) ?? [])];\n    const stems = constPrefixes.flatMap((constPrefix) => spellings.map((spelling) => constPrefix + spelling));\n    const reserved = stems.some((stem) => reservedList.some((name) => name.startsWith(stem)));\n    canonicalByPlainName.set(plain, reserved ? undefined : canonicalPath(rawPaths));\n  }\n\n  const resolved = new Map<string, string>();\n  for (const { key, path, method, plain } of candidates) {\n    const keepsPlainName = canonicalByPlainName.get(plain) === path;\n    resolved.set(key, keepsPlainName ? plain : derivePathModelBaseName(path, method, pathDisambiguator(path)));\n  }\n  return resolved;\n}\n\n/**\n * The one path in a group that is spelled most plainly by pathDeviation, or\n * undefined when two or more tie for it, so the choice never depends on the\n * order the paths were written in.\n */\nfunction canonicalPath(rawPaths: Iterable<string>): string | undefined {\n  let best: string | undefined;\n  let bestScore: PathDeviation | undefined;\n  let tied = false;\n  for (const path of rawPaths) {\n    const score = pathDeviation(path);\n    const cmp = bestScore ? compareDeviation(score, bestScore) : -1;\n    if (cmp < 0) {\n      best = path;\n      bestScore = score;\n      tied = false;\n    } else if (cmp === 0) {\n      tied = true;\n    }\n  }\n  return tied ? undefined : best;\n}\n\n/** See pathDeviation. */\ntype PathDeviation = [trailingSlash: number, customMethods: number, irregularSegments: number];\n\n/**\n * How far a raw path's spelling is from the plain prefix it flattens to:\n * `[trailing slash, custom methods written after a colon, literal segments\n * with any character outside a-z0-9]`, compared lexicographically. `/notes`\n * scores [0, 0, 0] and `/notes/` [1, 0, 0]; `/notes/{id}` scores [0, 0, 0]\n * and `/notes/by-id` [0, 0, 1]. A custom method is counted on its own rather\n * than as an irregular segment, so the slash form wins whatever the verb's\n * spelling: `/pets/{id}:adopt` scores [0, 1, 0] against `/pets/{id}/adopt`\n * at [0, 0, 0], and `/pets/{id}:batchAdopt` [0, 1, 1] against\n * `/pets/{id}/batchAdopt` at [0, 0, 1]. A parameter segment is never\n * irregular, whatever follows its braces, so a path without a colon scores\n * as it did before custom methods were read: `/tags/{tag}.json` and\n * `/tags/{tag}/json` still tie.\n */\nfunction pathDeviation(rawPath: string): PathDeviation {\n  const trailingSlash = rawPath.length > 1 && rawPath.endsWith('/') ? 1 : 0;\n  const segments = readPath(rawPath);\n  const customMethods = segments.filter((segment) => segment.customMethod).length;\n  const irregularSegments = segments.filter(\n    (segment) => !segment.text.startsWith('{') && /[^a-z0-9]/.test(segment.text),\n  ).length;\n  return [trailingSlash, customMethods, irregularSegments];\n}\n\nfunction compareDeviation(a: PathDeviation, b: PathDeviation): number {\n  return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];\n}\n\n/** The first six hex characters of the SHA-1 of a raw path. */\nfunction pathDisambiguator(rawPath: string): string {\n  return createHash('sha1').update(rawPath).digest('hex').slice(0, 6);\n}\n\n/**\n * The spellings a path-based prefix could take if a name derived from it were\n * run through one of the parser's cleaning steps: the prefix itself (every\n * path-derived name uses it verbatim), cleanSchemaName's form (lead-word\n * singularization plus backend and ListItem-marker stripping),\n * resolveSchemaName's form (the same plus the project's schemaNameTransform),\n * and stripListItemMarkers alone, which nested-model and inline-enum\n * qualification apply to a parent name. Reserving by every spelling is the\n * second line of defence behind \"use the base verbatim\": a cleaning step added\n * later cannot let a derived name slip past the reservation. Empty spellings\n * are dropped so a degenerate prefix cannot match every reserved name.\n */\nfunction prefixSpellings(prefix: string): string[] {\n  const spellings = [prefix, cleanSchemaName(prefix), resolveSchemaName(prefix), stripListItemMarkers(prefix)];\n  return [...new Set(spellings)].filter((spelling) => spelling.length > 0);\n}\n\n/**\n * The PascalCase const values an operationId-less operation can prepend to a\n * name minted from its prefix, read from the schemas its request body and 2xx\n * responses declare inline. A body `oneOf` variant pinning `kind: email`\n * yields `EmailTagsPostRequest` (deriveOneOfVariantName); a nested\n * `oneOf`/`anyOf` object variant yields `<Const><Parent><Field>`\n * (nameOneOfVariant, nameVariantModel). Every string const or single-value\n * enum of every inline object variant is collected, top level and nested — a\n * superset of whichever property each of those picks as the discriminator, so\n * the reservation can never be narrower than the naming. `$ref` targets are\n * components with names of their own and are not followed. A request body\n * `$ref` that cannot be resolved is left for buildOperation to report.\n *\n * Names that do not embed the prefix at all — a response `oneOf` variant\n * named from its bare const (`Email`, see deriveModelName in responses.ts)\n * or a `title`-mapped variant — are outside what a disambiguator can\n * separate and are not reserved here.\n */\nfunction collectOperationConstPrefixes(\n  op: OperationObject,\n  componentRequestBodies: Record<string, Record<string, unknown>> | undefined,\n  opLabel: string,\n): Set<string> {\n  const prefixes = new Set<string>();\n  let body: RequestBodyObject | undefined;\n  try {\n    body = resolveRequestBodyRef(op.requestBody, componentRequestBodies, opLabel);\n  } catch {\n    body = undefined;\n  }\n  collectConstPrefixes(selectRequestBodyContent(body)?.schema, prefixes, 0);\n  for (const [statusCode, response] of Object.entries(op.responses ?? {})) {\n    // Only a key `extractResponses` reads as a 2xx status code: a range, a\n    // fallback or a key OpenAPI does not define reserves nothing.\n    const responseKey = classifyResponseKey(statusCode);\n    if (responseKey.kind !== 'status' || responseKey.code < 200 || responseKey.code >= 300) continue;\n    // A `$ref` into `components/responses` has no `content` here and is not\n    // followed either: its inline body is named after the component, so the\n    // consts it pins never prefix a path-derived name.\n    for (const media of Object.values(response.content ?? {})) {\n      collectConstPrefixes(media?.schema, prefixes, 0);\n    }\n  }\n  return prefixes;\n}\n\nfunction collectConstPrefixes(schema: SchemaObject | undefined, out: Set<string>, depth: number): void {\n  if (!schema || schema.$ref || depth > 16) return;\n  for (const variants of [schema.oneOf, schema.anyOf]) {\n    for (const variant of variants ?? []) {\n      if (variant.$ref || !variant.properties) continue;\n      for (const property of Object.values(variant.properties)) {\n        const value = constStringOf(property);\n        const prefix = value === null ? '' : toPascalCase(value);\n        if (prefix) out.add(prefix);\n      }\n    }\n  }\n  const children: Array<SchemaObject | undefined> = [\n    ...(schema.oneOf ?? []),\n    ...(schema.anyOf ?? []),\n    ...(schema.allOf ?? []),\n    schema.items,\n    ...Object.values(schema.properties ?? {}),\n    typeof schema.additionalProperties === 'object' ? schema.additionalProperties : undefined,\n  ];\n  for (const child of children) {\n    collectConstPrefixes(child, out, depth + 1);\n  }\n}\n\n/** A property's pinned string value: a string `const`, or a single-value string `enum`. */\nfunction constStringOf(property: SchemaObject | undefined): string | null {\n  if (!property) return null;\n  if (typeof property.const === 'string') return property.const;\n  if (Array.isArray(property.enum) && property.enum.length === 1 && typeof property.enum[0] === 'string') {\n    return property.enum[0];\n  }\n  return null;\n}\n\nfunction deriveResponseName(op: OperationObject | undefined, pathModelBaseName: string): string {\n  if (op?.operationId) {\n    return operationIdModelName(op.operationId, 'Response');\n  }\n  return pathModelBaseName + 'Response';\n}\n\n/**\n * Element type of the array an overridden `dataPath` names in one response\n * body. The IR answers first — the detected data array itself, an envelope\n * companion's field (companion models included, so the parser's own item\n * model is reused and follows any later renaming), or the response model's\n * fields — and the document (`schema`, classified under `contextName`)\n * answers when the path crosses a model the parser has not materialized,\n * minting inline items under a path-derived name.\n */\nfunction resolveOverrideItemType(\n  result: ResponseExtractionResult,\n  schema: SchemaObject,\n  contextName: string,\n  dataPath: string,\n  componentModels: Model[],\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): { itemType: TypeRef; inlineModels: Model[] } | undefined {\n  if (dataPath === result.dataPath && result.itemType) return { itemType: result.itemType, inlineModels: [] };\n\n  const pool = [\n    ...result.inlineModels,\n    ...(result.envelopeCompanions ?? []).flatMap((companion) => companion.models),\n    ...componentModels,\n  ];\n  let fromIr: TypeRef | undefined;\n  if (result.envelopeFields) {\n    // The envelope was unwrapped, so its companions — not `result.response`,\n    // which is already the data array — are where the path starts.\n    const [head, ...rest] = dataPath.split('.');\n    const companion = result.envelopeFields.find((field) => field.name === head);\n    if (companion) fromIr = resolveDataPathItemType(companion.type, rest.join('.'), pool);\n  } else {\n    fromIr = resolveDataPathItemType(result.response, dataPath, pool);\n  }\n  if (fromIr) return { itemType: fromIr, inlineModels: [] };\n\n  return resolveDataPathFromSchema(schema, dataPath, contextName, componentSchemas, settle);\n}\n\n/** What the explicit pagination override asks of response extraction. */\ninterface PaginationExtractionOptions {\n  /**\n   * Nothing pages the operation — `strategy: 'none'`, or no query parameter\n   * drives an iterator and no override names one: keep a list envelope as a\n   * plain response model instead of unwrapping it.\n   */\n  disabled?: boolean;\n  /** An explicit `dataPath` to resolve to the element type of the array it names. */\n  dataPath?: string;\n  /**\n   * An explicit `endOfIteration` to check against the primary response\n   * (`decidePaginationOverride`): its path must land on a field whose type\n   * fits its kind, or the override is unusable.\n   */\n  endOfIteration?: PaginationEndOfIteration;\n  /** Component models, so the IR walk can follow a `$ref` wrapper's fields. */\n  componentModels?: Model[];\n  /**\n   * The override is the only source of an iterator: no query parameter\n   * yields one. A body its `dataPath` reaches no array in, or its\n   * `endOfIteration` resolves in to no field of the fitting type, is then\n   * kept as a plain response model too, since the override will be dropped\n   * (`buildOperation` warns) and nothing else pages the body. For the\n   * primary body that is exactly the case in which the override is dropped;\n   * a secondary 2xx body that cannot satisfy it is kept the same way.\n   */\n  overrideOnly?: boolean;\n}\n\n/** Whether the pagination override applies to the operation's responses, decided once against the primary body. */\ninterface PaginationOverrideDecision {\n  /**\n   * The override applies: its `dataPath` is handed to classification in\n   * every success body it reaches an array in, and its stop field is the\n   * iterator's.\n   */\n  usable: boolean;\n  /** Why it does not — the text `buildOperation` warns with; unset when it does. */\n  problem?: string;\n}\n\n/** One 2xx or 3xx entry, with the body `primaryBodySchema` picks from a 2xx (`{}` for a 3xx, which never types one). */\ninterface SuccessEntry {\n  code: number;\n  pick: ReturnType<typeof primaryBodySchema>;\n}\n\n/**\n * The primary response among the 2xx and 3xx entries — the one\n * `Operation.response` describes and the pagination override is decided\n * against — chosen by one rule, before any body is classified, so the two\n * never diverge: the lowest 2xx whose body is typed (`bodyIsTyped`), else\n * the lowest declared code (an untyped 2xx, or a 3xx when there is no 2xx).\n * `undefined` when no 2xx or 3xx is declared.\n */\nfunction primaryResponseEntry(\n  entries: readonly SuccessEntry[],\n  componentSchemas?: Record<string, SchemaObject>,\n): SuccessEntry | undefined {\n  const sorted = [...entries].sort((a, b) => a.code - b.code);\n  return sorted.find((entry) => entry.code < 300 && bodyIsTyped(entry.pick, componentSchemas)) ?? sorted[0];\n}\n\n/**\n * Whether a 2xx body will type as anything but `unknown` once classified: a\n * media type typed without a schema (binary, text), or a schema\n * classification types as something — asked of classification's own\n * reading of the body (`bodyTypesAsUnknown`: the same `$ref`, fold,\n * envelope, wrapper and `extractDirectResource` dispatch, ending on\n * `typesAsUnknown` where classification ends on `schemaToTypeRef`), before\n * any body is typed and without the warnings typing issues, so a body is\n * `unknown` after classification exactly when this says so before it.\n */\nfunction bodyIsTyped(\n  pick: ReturnType<typeof primaryBodySchema>,\n  componentSchemas?: Record<string, SchemaObject>,\n): boolean {\n  return pick.type !== undefined || (pick.schema !== undefined && !bodyTypesAsUnknown(pick.schema, componentSchemas));\n}\n\n/**\n * Accept or reject the override against the primary response, once, before any\n * success body is classified — the one check for the fields that depend on\n * the response, in the order `buildOperation` reports them: a `dataPath`\n * must reach an array in that body (`resolveDataPathFromSchema`, the walk\n * that later types the items), then an `endOfIteration` must resolve in it\n * to a field of the fitting type (`bodyEndOfIterationProblem`). An override\n * that sets neither asks nothing of the response and is usable; its\n * parameters were checked before the response was read\n * (`resolveOverrideParams`). No primary response (no `responses`, no 2xx or\n * 3xx), a primary without a body (a 204, or a 3xx when no 2xx is\n * declared) and a primary whose schema describes nothing resolve nothing,\n * so an override that sets either field is rejected against them.\n */\nfunction decidePaginationOverride(\n  pagination: PaginationExtractionOptions,\n  primary: SuccessEntry | undefined,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationOverrideDecision {\n  if (pagination.dataPath !== undefined) {\n    const reaches =\n      primary?.pick.schema !== undefined &&\n      resolveDataPathFromSchema(primary.pick.schema, pagination.dataPath, contextName, componentSchemas) !== undefined;\n    if (!reaches) {\n      return {\n        usable: false,\n        problem: `dataPath \"${pagination.dataPath}\" does not resolve to an array in the response`,\n      };\n    }\n  }\n  if (pagination.endOfIteration !== undefined) {\n    const problem = bodyEndOfIterationProblem(pagination.endOfIteration, primary?.pick.schema, componentSchemas);\n    if (problem !== undefined) return { usable: false, problem };\n  }\n  return { usable: true };\n}\n\n/**\n * The `components/responses` entry a response is written as a `$ref` to, or\n * undefined for an inline response. Only the outermost ref counts: it is the\n * name the operation uses, and the name a chain resolves through\n * (`resolveResponseRef`) stays the component's own business. The pointer is\n * matched whole and JSON Pointer escapes (RFC 6901 §4) undone, exactly as the\n * resolver does, so the name agrees with what it resolved.\n */\nfunction componentResponseNameOf(resp: ResponseObject | ReferenceObject): string | undefined {\n  if (!('$ref' in resp) || typeof resp.$ref !== 'string') return undefined;\n  const match = /^#\\/components\\/responses\\/(.+)$/.exec(resp.$ref);\n  return match?.[1].replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\n/**\n * The model name a response's inline body is shared under when the response\n * is written as a `$ref` into `components/responses`: the name\n * `resolveComponentResponseModelNames` settled on for the component, or\n * `componentResponseModelName` when no map was built. Undefined for a\n * response written inline, and for a ref no component answers — the\n * operation then names the body as it names an inline one, and the resolver\n * has already warned about the ref. The one answer for every place a\n * response can be written (workos/oagen#301): an explicit status code,\n * success or error, `default` and a `1XX`–`5XX` range read it alike, so a\n * component returned at a 404 by one operation and as `default` by another\n * names one model.\n */\nfunction sharedResponseModelName(\n  resp: ResponseObject | ReferenceObject,\n  ctx: ResponseTypingContext,\n): string | undefined {\n  const componentName = componentResponseNameOf(resp);\n  if (componentName === undefined) return undefined;\n  return ctx.componentResponseModelNames\n    ? ctx.componentResponseModelNames.get(componentName)\n    : componentResponseModelName(componentName);\n}\n\n/**\n * `<Component>Response`: the inline body of a response declared once under\n * `components/responses` and referenced from each operation that returns it.\n * It is named after the component, not the operation, so every referrer\n * shares one model (`PetFound` → `PetFoundResponse`) instead of minting a\n * `<Op>Response` copy each; the suffix is not doubled when the component is\n * already named `…Response`. Cleaned like an operationId-derived name, so\n * the stem (`componentResponseModelBase`) prefixes everything derived from\n * it — a list's `<Component>Item`, nested `<Component>Response…` models,\n * and the component's secondary bodies and headers\n * (`<Component><MediaType>Response`, `<Component><Header>`; see\n * `responseModelSite`).\n */\nfunction componentResponseModelName(componentName: string): string {\n  const base = toPascalCase(componentName);\n  return cleanSchemaName(base.endsWith('Response') ? base : base + 'Response');\n}\n\n/** What a component response's inline body is named, and every model name it mints under that name. */\ninterface ComponentResponseNaming {\n  name: string;\n  /** The root model and everything nested under it, envelope companions included; empty for a body without a schema. */\n  minted: readonly string[];\n}\n\n/**\n * The model name each component response's inline body is shared under,\n * decided once for the document: `componentResponseModelName`, stepped to the\n * first numbered form (`OwnerCardResponse2`, `…3`) under which neither it nor\n * any model the body mints — a nested object (`OwnerCardResponse2Detail`),\n * array items, union variants, envelope companions — is a name a component\n * schema (or a model a component field mints) or an earlier component\n * response already owns: `OwnerCard` beside a schema `OwnerCardResponse`, or\n * beside a schema `OwnerCardResponse2Detail`, or beside a component response\n * `OwnerCardResponse`. A shared name of another shape would otherwise be\n * folded by the later merge, which compares field names, onto a model with\n * other field types, silently; and naming such a body per operation instead\n * would hand two shared bodies of one operation (`OwnerCard` at 200,\n * `NewOwner` at 201) the same `<Op>Response`. The names are read with the\n * extractor the operation will use, under the candidate name and under\n * every reading an operation can give the body — a list envelope unwrapped\n * for an iterator (`NotePageItem`) or kept as the wire shape\n * (`NotePageResponse`, `NotePageResponseData`), since which one an\n * operation takes (`iteratorSource`) is known only when it is read and two\n * operations returning the same body can differ — so the whole body moves\n * together and the reference and the models agree by\n * construction; a chain of refs is followed to the body silently, since the\n * operation declaring the ref reports a bad one when it reads it. A clash the\n * stem does not reach — a titled variant, named the same under any stem —\n * stops the stepping, and the merge passes settle it as for any operation\n * body. A component already named like its derived name\n * (`OwnerCardResponse` → `OwnerCardResponse`) keeps it ahead of one that\n * only derives it; the rest are decided in document order, so the outcome\n * never depends on which operation is read first. Every component ends up in\n * the map, so every operation that returns it shares the one model.\n */\nfunction resolveComponentResponseModelNames(\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  takenModels: readonly Model[],\n  componentSchemas?: Record<string, SchemaObject>,\n): ReadonlyMap<string, ComponentResponseNaming> {\n  const taken = new Set(takenModels.map((model) => model.name));\n  const componentNames = Object.keys(componentResponses ?? {});\n  const exact = componentNames.filter((name) => componentResponseModelName(name) === name);\n  const ordered = [...exact, ...componentNames.filter((name) => !exact.includes(name))];\n  const names = new Map<string, ComponentResponseNaming>();\n  for (const componentName of ordered) {\n    const schema = componentResponseBodySchema(componentName, componentResponses ?? {});\n    const mintedUnder = (name: string): string[] => (schema ? bodyModelNames(schema, name, componentSchemas) : []);\n    const base = componentResponseModelName(componentName);\n    let name = base;\n    let minted = mintedUnder(name);\n    let previous: string[] | undefined;\n    // Unbounded on purpose: `taken` is finite and every step is a new\n    // numbered stem, so a free one is always reached; only a clash the stem\n    // does not reach (`stuck`) ends the search without one.\n    for (let n = 2; ; n++) {\n      const clashing = [name, ...minted].filter((candidate) => taken.has(candidate));\n      if (clashing.length === 0) break;\n      const stuck =\n        previous !== undefined && clashing.length === previous.length && clashing.every((c) => previous!.includes(c));\n      if (stuck) break;\n      previous = clashing;\n      name = `${base}${n}`;\n      minted = mintedUnder(name);\n    }\n    taken.add(name);\n    for (const minted_ of minted) taken.add(minted_);\n    names.set(componentName, { name, minted });\n  }\n  return names;\n}\n\n/** The schema a component response's body is read from, through a chain of refs, silently; undefined without one. */\nfunction componentResponseBodySchema(\n  componentName: string,\n  componentResponses: Record<string, Record<string, unknown>>,\n): SchemaObject | undefined {\n  const component = componentResponses[componentName];\n  if (!component) return undefined;\n  const resolved = resolveResponseRef<ResponseObject>(\n    component as ResponseObject | ReferenceObject,\n    componentResponses,\n    `components/responses/${componentName}`,\n    'override',\n    'silent',\n  );\n  return primaryBodySchema(resolved).schema;\n}\n\n/**\n * Every model name a response body mints under `contextName`, under every\n * reading an operation can give it (`BODY_READINGS`): the extractor's models\n * and its envelope companions' when a list envelope is unwrapped\n * (`NotePageItem`), and the plain model's nested models when it is kept as\n * the wire shape (`NotePageResponse`, `NotePageResponseData`). Which reading\n * each operation takes is decided when it is read (`iteratorSource`), and two\n * operations returning one component response can take different ones, so\n * both sets are reserved and the stem steps when either clashes.\n */\nfunction bodyModelNames(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): string[] {\n  const names = new Set<string>();\n  for (const reading of BODY_READINGS) {\n    const body = classifyAndExtractResponse(schema, contextName, componentSchemas, reading);\n    for (const model of body.inlineModels) names.add(model.name);\n    for (const companion of body.envelopeCompanions ?? []) for (const model of companion.models) names.add(model.name);\n  }\n  return [...names];\n}\n\n/**\n * The stem every model derived from a component response starts with (see\n * operationIdModelBase for the argument): the body (`CardResponse`, or the\n * `CardResponse2` it steps to) and the models nested under it, an inline\n * body under another media type (`CardApplicationYamlResponse`) and an\n * object-shaped header (`CardXMeta`), the last two named from the shared\n * body name less its `Response` (`responseModelSite`), which starts with\n * this stem. Reserved by resolvePathModelBaseNames so no path-derived name\n * takes it.\n */\nfunction componentResponseModelBase(componentName: string): string {\n  return cleanSchemaName(toPascalCase(componentName).replace(/Response$/, ''));\n}\n\n/**\n * Media types the fixed-order response pick types as a plain string without\n * reading their schema, in the order it checks them.\n */\nconst TEXT_RESPONSE_MEDIA_TYPES: readonly string[] = ['text/plain', 'text/html', 'text/xml', 'application/xml'];\n\n/** Where an inline body declared for a secondary media type gets its name (`typeSecondaryContent`). */\ninterface ContentModelNaming {\n  /**\n   * The stem the media type's token follows (`ResponseModelSite.stem`): the\n   * operation's (`RenderPetCard`; with the response's label for a `default`\n   * or `1XX`–`3XX` range, `ListPetsDefault`), a component response's\n   * (`Card`), or an inline error entry's body name (`GetNoteError404`,\n   * `GetNoteError4Xx`).\n   */\n  base: string;\n  /**\n   * How the body is named and steps. `Response`: `<base><MediaType>Response`\n   * (`RenderPetCardTextHtmlResponse`), deferred as `content` — a success\n   * entry, a `default` or `1XX`–`3XX` range, and a component response\n   * wherever it is mounted. `Error`: `<base><MediaType>`\n   * (`GetNoteError404ApplicationYaml`), deferred as `error`, the kind the\n   * entry's JSON body steps by — an inline error entry, at a 4xx/5xx status\n   * code or in a `4XX`/`5XX` range.\n   */\n  role: 'Response' | 'Error';\n  /** A status code, the key of a `4XX`/`5XX` range (`4XX`), or the label of a `default` or `1XX`–`3XX` response (`Default`, `Success`). */\n  statusCode: number | string;\n  /** Set for a component response's body: a component site (`componentSite`), stepping by number on a clash. */\n  shared: boolean;\n}\n\n/**\n * Where the models a response declares besides its primary body — an inline\n * object under another media type, an object-shaped header — get their\n * names (`responseModelSite`). The primary body's own name is decided\n * elsewhere (`componentResponseModelName`, `deriveResponseName`,\n * `deriveErrorModelName`, `deriveFallbackResponseName`).\n */\ninterface ResponseModelSite {\n  /**\n   * The stem every such model starts with: the entry's body name less a\n   * trailing `Response` — the shared body name for a response written as a\n   * `$ref` into `components/responses` (`CardResponse` → `Card`), else the\n   * name the entry's own inline body is materialized under: `<Op>Response`\n   * for a success or redirect entry (`GetNote`), `<Op><Label>Response` for\n   * a `default` or `1XX`–`3XX` range (`ListPetsDefault`), and the error\n   * body's `<Op>Error<code>` for a 4xx/5xx status code or a `4XX`/`5XX`\n   * range (`GetNoteError404`, `GetNoteError4Xx`), which has no `Response`\n   * to drop.\n   */\n  stem: string;\n  /**\n   * Set for a component response: its models are named from the component\n   * alone, so the same names come out of every operation that returns it, at\n   * whatever status code or fallback key, and the shape registry shares one\n   * model among them; on a clash they step by number (`componentSite`), so\n   * the stepped name depends on the component alone too.\n   */\n  shared: boolean;\n  /** What qualifies a header's models: `stem` for a component response, the service for an inline one; none without a service. */\n  headerParent: string | undefined;\n}\n\n/**\n * Decide where everything a response declares besides its primary body is\n * named from: the stem is the entry's body name less a trailing `Response`.\n * A response written as a `$ref` into `components/responses` is one thing\n * however many operations return it and whatever key each mounts it at, so\n * an inline object under another media type and an object-shaped header are\n * named from the model its body is shared under (`componentModelName`, see\n * `sharedResponseModelName`): `Card` + `ApplicationYaml` + `Response` for\n * the body under `application/yaml`, `Card` + `XMeta` for an `X-Meta`\n * header, and `CardResponse2…` when the body stepped to `CardResponse2` —\n * the same names from `GET /notes` at 200, from `GET /pets` at 404 and from\n * a `default` or `4XX` that refs it, so every operation shares one model of\n * each (workos/oagen#302). An inline response's are named from the name its\n * own body is materialized under (`bodyName`): `<Op>Response` for a success\n * or redirect entry and `<Op><Label>Response` for a `default` or `1XX`–`3XX`\n * range give `GetNoteApplicationYamlResponse` and\n * `ListPetsDefaultTextPlainResponse`; `<Op>Error<code>` for an error entry\n * — a 4xx/5xx status code or a `4XX`/`5XX` range — gives\n * `GetNoteError404ApplicationYaml` and `GetNoteError4XxApplicationYaml`,\n * with the status code or range key always in the name, as it is in the\n * JSON body's (workos/oagen#304); a header is the service plus header name\n * (`NotesXMeta`) whatever the entry. The names of either kind go through the\n * shape registry as before (`resolveDeferredInlineTypes`), so one a\n * component schema or another site owns with a shape it does not share\n * steps: an inline response's to the kind's next candidate, by status code,\n * operation or `Body`; a component's by number (`CardXMeta2`,\n * `CardApplicationYamlResponse2`), as its body steps to `CardResponse2`, so\n * the stepped name still depends on the component alone (`componentSite`).\n */\nfunction responseModelSite(\n  componentModelName: string | undefined,\n  bodyName: string,\n  ctx: ResponseTypingContext,\n): ResponseModelSite {\n  const stem = (componentModelName ?? bodyName).replace(/Response$/, '');\n  if (componentModelName !== undefined) return { stem, shared: true, headerParent: stem };\n  return {\n    stem,\n    shared: false,\n    headerParent: ctx.serviceName ? toPascalCase(ctx.serviceName) : undefined,\n  };\n}\n\n/**\n * The naming of an inline body under a secondary media type of one response\n * entry: the site's stem, then the entry's role — `Error` for an error\n * entry (a 4xx/5xx status code, a `4XX`/`5XX` range), `Response` otherwise\n * — except that a component response's bodies are `Response` at any key, as\n * its primary body is `<Component>Response` whether an operation mounts it\n * at 200, at 404 or in a `4XX` range.\n */\nfunction contentModelNaming(\n  site: ResponseModelSite,\n  role: 'Response' | 'Error',\n  statusCode: number | string,\n): ContentModelNaming {\n  return { base: site.stem, role: site.shared ? 'Response' : role, statusCode, shared: site.shared };\n}\n\n/**\n * Read a response's `content` map into the media types it declares — in\n * document order and verbatim, parameters, vendor suffixes and wildcards\n * included — with a type for each. A media type is typed the way `response`\n * is when it is the only one declared, so the entry for `primaryContentType`\n * (the one the fixed-order pick read `primaryType` from) carries that very\n * TypeRef and every other entry goes through `typeSecondaryContent`. Returns\n * `undefined` when the response declares no media type at all, so the caller\n * leaves both keys off.\n */\nfunction extractResponseContents(\n  content: Record<string, { schema?: SchemaObject }> | undefined,\n  primaryContentType: string | undefined,\n  primaryType: TypeRef | undefined,\n  naming: ContentModelNaming,\n  ctx: ResponseTypingContext,\n): { contentTypes: string[]; contents: ResponseContent[] } | undefined {\n  if (!content) return undefined;\n  const contentTypes = Object.keys(content);\n  if (contentTypes.length === 0) return undefined;\n  const contents = contentTypes.map((contentType) => {\n    const entry: ResponseContent = { contentType, type: { kind: 'primitive', type: 'unknown' } };\n    entry.type =\n      primaryType !== undefined && contentType === primaryContentType\n        ? primaryType\n        : typeSecondaryContent(contentType, content[contentType]?.schema, naming, ctx, entry, contentTypes);\n    return entry;\n  });\n  return { contentTypes, contents };\n}\n\n/**\n * Type a media type the fixed-order pick did not choose, exactly as it would\n * have been typed had it been the only one declared: `application/octet-stream`\n * and `application/pdf` are binary and the text and XML types are strings\n * whatever their schema says, any other media type is typed from its schema,\n * and one without a schema is `unknown`. The one addition is that an inline\n * object under such a media type is materialized — the primary pick's name\n * belongs to the primary body, so this one is named after its media type as\n * well, from the stem and role `naming` carries (`responseModelSite`,\n * `contentModelNaming`): `RenderPetCardTextHtmlResponse` for a success\n * entry, `CardApplicationYamlResponse` for a response shared through\n * `components/responses`, and `GetNoteError404ApplicationYaml` or\n * `GetNoteError4XxApplicationYaml` for an inline error entry, whose bodies\n * are deferred as `error` so they step by `Body` as the entry's JSON body\n * does — with the media type's fragment taken from its essence among its\n * `siblings` (the response's content keys), so a key keeps its model name\n * however it is spelled and two spellings of one essence side by side are\n * told apart by their parameters (`mediaTypeNameFragment`). That naming\n * waits for every primary model\n * (`resolveDeferredInlineTypes`), so a schema is deferred and `target.type`\n * — returned here as a placeholder — filled in then.\n */\nfunction typeSecondaryContent(\n  contentType: string,\n  schema: SchemaObject | undefined,\n  naming: ContentModelNaming,\n  ctx: ResponseTypingContext,\n  target: ResponseContent,\n  siblings: readonly string[],\n): TypeRef {\n  // Parameters and case do not change what a body is: `application/pdf;\n  // version=1.7` is as binary as `application/pdf`, `TEXT/PLAIN; charset=utf-8`\n  // as much a string as `text/plain`. The key itself stays as written.\n  const essence = mediaTypeEssence(contentType);\n  if (essence === 'application/octet-stream' || essence === 'application/pdf') {\n    return { kind: 'primitive', type: 'string', format: 'binary' };\n  }\n  if (TEXT_RESPONSE_MEDIA_TYPES.includes(essence)) return { kind: 'primitive', type: 'string' };\n  if (!schema) return { kind: 'primitive', type: 'unknown' };\n  const fragment = mediaTypeNameFragment(contentType, siblings);\n  ctx.deferred.push({\n    kind: naming.role === 'Error' ? 'error' : 'content',\n    schema,\n    name: naming.role === 'Error' ? `${naming.base}${fragment}` : `${naming.base}${fragment}Response`,\n    statusCode: naming.statusCode,\n    operationQualifier: ctx.operationQualifier,\n    componentSchemas: ctx.componentSchemas,\n    targets: [target],\n    ...(naming.shared && { componentSite: true }),\n  });\n  return target.type;\n}\n\n/**\n * `<Op>DefaultResponse`, `<Op>SuccessResponse`: the inline body of a\n * `default` or `1XX`–`3XX` response, named like the primary body's\n * `<Op>Response` with the response's label (`Default`, or the word for its\n * range) in between. A `4XX` or `5XX` body is an error body and is named\n * `<Op>Error4Xx` instead (`deriveErrorModelName`, `isErrorStatusRange`).\n * Starts with the operation's stem, so `operationIdModelBase` reserves it\n * with the rest. A fallback written as a `$ref` into `components/responses`\n * is named after the component instead (`sharedResponseModelName`).\n */\nfunction deriveFallbackResponseName(op: OperationObject | undefined, pathModelBaseName: string, label: string): string {\n  if (op?.operationId) {\n    return operationIdModelName(op.operationId, `${label}Response`);\n  }\n  return `${pathModelBaseName}${label}Response`;\n}\n\n/**\n * The model name an inline error body is materialized under: the operation's\n * stem plus `Error<code>` — the status code (`GetPetError404`) or, for a\n * `4XX`/`5XX` range, the range key in PascalCase (`GetPetError4Xx`) — so two\n * operations' inline 404s never share one model, nor do two status codes or\n * a status code and a range of one operation. The one source of every\n * inline error body's name: the JSON body of a 4xx/5xx status code\n * (`extractResponses`), of a `4XX`/`5XX` range (`fillFallbackResponse`), and\n * through `responseModelSite` the bodies of their secondary media types\n * (`GetPetError404ApplicationYaml`), so the status code is in every one of\n * them (workos/oagen#304). Built by the rule `deriveResponseName` uses for\n * `<Op>Response`: `operationIdModelName` when the operation has an\n * `operationId`, else the path-derived prefix (`PetsByPetIdGetError404`),\n * which `resolvePathModelBaseNames` already keeps clear of every component\n * schema name.\n */\nfunction deriveErrorModelName(\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  code: number | StatusRange,\n): string {\n  // A range key is cased as every identifier is (`toPascalCase`: `4XX` →\n  // `4Xx`), which is what the extractor makes of the name anyway; a status\n  // code is digits and stays as written.\n  const suffix = `Error${typeof code === 'number' ? code : toPascalCase(code)}`;\n  if (op?.operationId) {\n    return operationIdModelName(op.operationId, suffix);\n  }\n  return `${pathModelBaseName}${suffix}`;\n}\n\n/**\n * Where the fallback responses (`default`, `1XX`–`5XX`) of one operation\n * land while its responses are read, with what typing their bodies and\n * headers needs. An entry is attached as its key is read; a body with an\n * inline schema is deferred like a header's (`typeFallbackBody` for\n * `default` and `1XX`–`3XX`, `typeErrorBody` for `4XX` and `5XX`) and its\n * `type` filled in once every operation has been read.\n */\ninterface FallbackResponseSink {\n  op: OperationObject | undefined;\n  pathModelBaseName: string;\n  opLabel: string;\n  ctx: ResponseTypingContext;\n  defaultResponse?: DefaultResponse;\n  /** In document order. */\n  rangeResponses: RangeResponse[];\n}\n\n/**\n * Read a Responses Object key that is not a status code into `sink`:\n * `default` and a range are kept; an `x-` key is a specification extension\n * and carries no response; a key OpenAPI does not define (`error`, `6XX`,\n * `600` — see `classifyResponseKey`) is warned about, then ignored, instead\n * of being dropped silently. A status code never reaches here: the caller\n * reads it into `successResponses` or `errors`.\n */\nfunction readFallbackResponse(\n  responseKey: Exclude<ResponseKey, { kind: 'status' }>,\n  key: string,\n  resp: ResponseObject | ReferenceObject,\n  sink: FallbackResponseSink,\n): void {\n  if (responseKey.kind === 'extension') return;\n  if (responseKey.kind === 'unrecognized') {\n    warnUnrecognizedResponseKey(key, sink.opLabel);\n    return;\n  }\n  const range = responseKey.kind === 'range' ? responseKey.range : undefined;\n  if (range && sink.rangeResponses.some((entry) => entry.range === range)) {\n    // `4XX` and `4xx` side by side: JSON allows the pair, OpenAPI does not.\n    console.warn(`[oagen] Warning: Duplicate \"${range}\" response on ${sink.opLabel}; keeping the first`);\n    return;\n  }\n  // The bundler leaves `$ref: '#/components/responses/…'` in place, and a\n  // Reference Object has no `headers` or `content` of its own to read.\n  const resolved = resolveResponseRef<ResponseObject>(\n    resp,\n    sink.ctx.componentResponses,\n    `${key} response of ${sink.opLabel}`,\n    sink.ctx.refSiblingDescriptions,\n  );\n  // A ref into `components/responses` names the body after the component,\n  // as it does at a status code, so every operation that returns the\n  // component — at any status, `default` or a range — shares one model; its\n  // secondary bodies and headers follow the same name (`responseModelSite`).\n  const componentModelName = sharedResponseModelName(resp, sink.ctx);\n  // The entry is filled in place: a deferred body's `type` lands on this\n  // very object once every operation has been read.\n  if (range) {\n    const entry: RangeResponse = { range };\n    fillFallbackResponse(entry, resolved, range, sink, componentModelName);\n    sink.rangeResponses.push(entry);\n  } else {\n    const entry: DefaultResponse = {};\n    fillFallbackResponse(entry, resolved, undefined, sink, componentModelName);\n    sink.defaultResponse = entry;\n  }\n}\n\n/**\n * Read the body, media types and headers of one fallback response onto\n * `entry`; a key is left off when absent (`range` is unset for `default`).\n * The body of a `default` or `1XX`–`3XX` response is named after the\n * operation and the response's label (`deriveFallbackResponseName`) and\n * deferred as a fallback body (`typeFallbackBody`); the body of a `4XX` or\n * `5XX` response is an error body (`isErrorStatusRange`), named\n * `<Op>Error4Xx` and deferred exactly as a 404's is (`deriveErrorModelName`,\n * `typeErrorBody`), with the range key where that has the status code, so\n * it steps by `Body` as that does (workos/oagen#304). A response that is a\n * `$ref` into `components/responses` is named after the component instead\n * (`componentModelName`, see `sharedResponseModelName`), the name every\n * operation returning the component shares, whichever kind of site it is.\n * The body is read before the headers so its deferred models are named\n * first, as they were when every fallback body was typed ahead of every\n * header. The media types are read exactly as a success entry's: every one\n * declared, the one `type` was read from sharing its TypeRef, each other\n * typed on its own — an inline object under `text/plain` of the `default`\n * response is `<Op>DefaultTextPlainResponse`, under `application/yaml` of a\n * `4XX` response `<Op>Error4XxApplicationYaml`. The secondary bodies and\n * headers of a response written as a `$ref` into `components/responses` are\n * named from the component's shared body name (`responseModelSite`), as an\n * explicit status code's are.\n */\nfunction fillFallbackResponse(\n  entry: DefaultResponse | RangeResponse,\n  resp: ResponseObject,\n  range: StatusRange | undefined,\n  sink: FallbackResponseSink,\n  componentModelName: string | undefined,\n): void {\n  const label = range === undefined ? 'Default' : STATUS_RANGE_LABELS[range];\n  // The key a `4XX`/`5XX` body is named and qualified by, as a 404's is by\n  // its status code; a `default` or `1XX`–`3XX` body is named by its label.\n  const errorRange = range !== undefined && isErrorStatusRange(range) ? range : undefined;\n  const operationName =\n    errorRange === undefined\n      ? deriveFallbackResponseName(sink.op, sink.pathModelBaseName, label)\n      : deriveErrorModelName(sink.op, sink.pathModelBaseName, errorRange);\n  const contextName = componentModelName ?? operationName;\n  const componentSite = componentModelName !== undefined;\n  const site = responseModelSite(componentModelName, operationName, sink.ctx);\n  const json = jsonResponseSchema(resp);\n  // Shared by reference with the deferred body, so the content entry of the\n  // media type `type` was read from can join it once it exists.\n  const targets: Array<{ type?: TypeRef }> = [entry];\n  if (json) {\n    entry.type =\n      errorRange === undefined\n        ? typeFallbackBody(json.schema, contextName, label, sink, targets, componentSite)\n        : typeErrorBody(json.schema, contextName, errorRange, sink.ctx, targets, componentSite);\n  }\n  const contents = extractResponseContents(\n    resp.content,\n    json?.contentType,\n    entry.type,\n    errorRange === undefined\n      ? contentModelNaming(site, 'Response', label)\n      : contentModelNaming(site, 'Error', errorRange),\n    sink.ctx,\n  );\n  if (contents) {\n    entry.contentTypes = contents.contentTypes;\n    entry.contents = contents.contents;\n    const own = contents.contents.find((content) => content.contentType === json?.contentType);\n    if (own) targets.push(own);\n  }\n  const headers = extractResponseHeaders(resp.headers, sink.opLabel, label, sink.ctx, site);\n  if (headers) entry.headers = headers;\n  // The response's own `description`, read as for a success or error entry —\n  // a sibling beside a `$ref` included, since `resolveResponseRef` kept it.\n  const description = presentText(resp.description);\n  if (description) entry.description = description;\n}\n\n/**\n * Type a fallback body and materialize every model it names, under a name no\n * other model owns. A `$ref` is the referenced model. An inline schema is\n * deferred like a header's or a secondary body's: once every operation has\n * been read (`resolveDeferredInlineTypes`) it is extracted as if it were a\n * field named `contextName` of a parent with no name, through the extractor\n * every field goes through — so every shape a field can take (a nullable\n * object, an array or map of objects, `oneOf`/`anyOf` variants, an `allOf`\n * merge, nested objects) is materialized under the name `schemaToTypeRef`\n * references it by, by construction — and checked against the spec-wide\n * registry, so a component, or another operation's body, that happens to be\n * named like the fallback is never overwritten by `mergeInlineResponseModels`:\n * a clash moves the whole body to the next free name (`<Op>DefaultResponse2`,\n * `…3`), nested models and ref together. A body a `components/responses`\n * entry declares (`componentSite`) is named after the component\n * (`<Component>Response`) and shares the model of every other site that\n * returns the component, whatever its kind. List envelope and\n * resource-wrapper detection are skipped on purpose: a fallback body is not\n * what the SDK method returns, so it must not drive pagination. Returns the\n * placeholder the resolution replaces on `target`.\n */\nfunction typeFallbackBody(\n  schema: SchemaObject,\n  contextName: string,\n  label: string,\n  sink: FallbackResponseSink,\n  targets: Array<{ type?: TypeRef }>,\n  componentSite: boolean,\n): TypeRef {\n  if (schema.$ref) return schemaToTypeRef(schema, contextName);\n  sink.ctx.deferred.push({\n    kind: 'fallback',\n    schema,\n    name: contextName,\n    statusCode: label,\n    operationQualifier: sink.ctx.operationQualifier,\n    componentSchemas: sink.ctx.componentSchemas,\n    targets,\n    ...(componentSite && { componentSite }),\n  });\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/**\n * Type an error response's JSON body and materialize every model it names,\n * under a name no other model owns (workos/oagen#236: `schemaToTypeRef` alone\n * named a model — `Error404` — that nothing created). A `$ref` is the\n * referenced model. An inline schema is deferred exactly like a fallback\n * body's (`typeFallbackBody`): once every operation has been read\n * (`resolveDeferredInlineTypes`) it is extracted as if it were a field named\n * `contextName` of a parent with no name, so every shape a field can take — a\n * plain or nullable object, an array or map of objects, `oneOf`/`anyOf`\n * variants (`GetPetError400`, `GetPetError400WithCode`,\n * `AuthGetPetError400`), an `allOf` merge with `$ref` branches, nested\n * objects (`GetPetError404Details`) — is materialized under the name\n * `schemaToTypeRef` references it by, by construction, and checked against\n * the spec-wide registry: a name a component schema, a model nested in one\n * (`GetPet.error404` owns `GetPetError404`), a header or another operation's\n * body already owns with a shape it does not share moves the whole body to\n * the next free name (`GetPetError404Body`, `…Body2`), nested models and ref\n * together; a shape the owner shares (`ownerShares`) takes the name. A\n * titled variant that clashes (`Circle`) is\n * reserved and qualified (`CircleGetPetError400`), as under any deferred\n * kind. A body that is itself an inline enum, or an array of one, mints no\n * model and is promoted to `spec.enums` by `collectInlineEnumsFromOperations`.\n * A body a `components/responses` entry declares (`componentSite`) is named\n * after the component (`<Component>Response`) and steps by number\n * (`<Component>Response2`) rather than by `Body`, the way the same\n * component's body steps at a `default` or range site, so every site that\n * returns the component settles on one model. The body of a `4XX` or `5XX`\n * range comes through here too (`fillFallbackResponse`), under\n * `<Op>Error4Xx` with the range key as `code`, so it is named, stepped and\n * qualified exactly as a 404's body is; and so does an error entry's body\n * under a secondary media type (`typeSecondaryContent`), under\n * `<Op>Error<code><MediaType>`. List envelope and resource-wrapper\n * detection are skipped on purpose, as for a fallback body. Returns the\n * placeholder the resolution replaces on every target.\n */\nfunction typeErrorBody(\n  schema: SchemaObject,\n  contextName: string,\n  code: number | StatusRange,\n  ctx: ResponseTypingContext,\n  targets: Array<{ type?: TypeRef }>,\n  componentSite: boolean,\n): TypeRef {\n  if (schema.$ref) return schemaToTypeRef(schema, contextName);\n  ctx.deferred.push({\n    kind: 'error',\n    schema,\n    name: contextName,\n    statusCode: code,\n    operationQualifier: ctx.operationQualifier,\n    componentSchemas: ctx.componentSchemas,\n    targets,\n    ...(componentSite && { componentSite }),\n  });\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/**\n * The fixed-order pick of a success response's body: the JSON schema when a\n * JSON media type is declared (`application/json` by essence, then `+json`);\n * else a binary (`application/octet-stream`, `application/pdf`) or text\n * (`TEXT_RESPONSE_MEDIA_TYPES`) media type, typed as a string without reading\n * its schema; else the first media type that declares a schema; else the\n * first declared, which reads as `unknown`. Media types are compared by\n * essence (`application/pdf; foo=bar` is as binary as `application/pdf`,\n * `TEXT/PLAIN; charset=utf-8` as much a string as `text/plain`) and\n * `contentType` is the key as written. `extractResponses` reads a 2xx body\n * through this, and `resolvePathModelBaseNames` asks the same question of a\n * component response, so the names it reserves are the ones the operation\n * will mint, whatever media type the body is declared under.\n */\nfunction primaryBodySchema(resp: ResponseObject): { contentType?: string; schema?: SchemaObject; type?: TypeRef } {\n  const json = jsonResponseSchema(resp);\n  if (json) return { contentType: json.contentType, schema: json.schema };\n  const content = resp.content;\n  if (!content) return {};\n  const keyWithEssence = (essence: string): string | undefined =>\n    Object.keys(content).find((contentType) => mediaTypeEssence(contentType) === essence);\n  const binaryKey = keyWithEssence('application/octet-stream') ?? keyWithEssence('application/pdf');\n  if (binaryKey) return { contentType: binaryKey, type: { kind: 'primitive', type: 'string', format: 'binary' } };\n  const textKey = TEXT_RESPONSE_MEDIA_TYPES.map(keyWithEssence).find((key) => key !== undefined);\n  if (textKey) return { contentType: textKey, type: { kind: 'primitive', type: 'string' } };\n  // The first media type that declares a schema; when none does, the first\n  // declared is the primary and reads as unknown.\n  const entries = Object.entries(content);\n  const first = entries.find(([, media]) => media?.schema) ?? entries[0];\n  return first ? { contentType: first[0], schema: first[1]?.schema } : {};\n}\n\n/**\n * The schema of a response's JSON body, with the media type it was declared\n * under as written: `application/json` first, else a `+json` media type\n * (`application/problem+json` is the usual shape of a `default` error),\n * matched by essence — parameters (`; charset=utf-8`) stripped, case folded.\n * Other media types type nothing, for an error entry as for a fallback.\n */\nfunction jsonResponseSchema(resp: ResponseObject): { contentType: string; schema: SchemaObject } | undefined {\n  const entries = Object.entries(resp.content ?? {}).filter(([, media]) => media?.schema);\n  // The one JSON rule requests and responses share (`isJsonMediaType`):\n  // `application/json` itself first, then any `+json` type.\n  const match =\n    entries.find(([mediaType]) => isPlainJsonMediaType(mediaType)) ??\n    entries.find(([mediaType]) => isJsonMediaType(mediaType));\n  return match && match[1].schema ? { contentType: match[0], schema: match[1].schema } : undefined;\n}\n\n/**\n * The type of a body the document does not describe:\n * `{ kind: 'primitive', type: 'unknown' }`. A 3xx entry's `type` is always\n * this; a 2xx entry's is this until a media-type rule types it; and an\n * operation's `response` is this when the operation declares no 2xx or 3xx\n * response at all — only `default`, ranges or errors, an empty `responses`\n * map, or no `responses` key — so an emitter never types a return value the\n * document does not describe. Each call returns a new object.\n */\nfunction undescribedBodyType(): TypeRef {\n  return { kind: 'primitive', type: 'unknown' };\n}\n\nfunction extractResponses(\n  responses: Record<string, ResponseObject> | undefined,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  path?: string,\n  method?: HttpMethod,\n  componentSchemas?: Record<string, SchemaObject>,\n  ctx: ResponseTypingContext = { operationQualifier: '', deferred: [] },\n  pagination: PaginationExtractionOptions = {},\n): {\n  response: TypeRef;\n  responseHeaders?: ResponseHeader[];\n  responseContentTypes?: string[];\n  responseContents?: ResponseContent[];\n  responseDescription?: string;\n  /** The status code of the entry `response` was read from; undefined when no 2xx/3xx is declared. */\n  responseStatusCode?: number;\n  successResponses?: SuccessResponse[];\n  errors: ErrorResponse[];\n  /** The `default` response, when the operation declares one. */\n  defaultResponse?: DefaultResponse;\n  /** The `1XX`–`5XX` range responses in declaration order, when the operation declares any. */\n  rangeResponses?: RangeResponse[];\n  inlineModels: Model[];\n  isPaginated: boolean;\n  dataPath?: string;\n  dataDescription?: string;\n  itemType?: TypeRef;\n  envelopeFields?: Field[];\n  endOfIteration?: PaginationEndOfIteration;\n  /** Element type of the array the override's `dataPath` names; unset when the override was rejected or names none. */\n  overrideItemType?: TypeRef;\n  /**\n   * Why the override cannot apply to the primary response — a `dataPath`\n   * that reaches no array in it, or an `endOfIteration` that resolves in it\n   * to no field of the fitting type — in the words `buildOperation` warns\n   * with (`decidePaginationOverride`); unset when it can, or when it sets\n   * neither field.\n   */\n  overrideProblem?: string;\n  envelopeCompanions?: EnvelopeCompanion[];\n  /** The primary body is a list envelope kept as a plain response model because nothing pages it (`ResponseExtractionResult.unpagedEnvelope`). */\n  unpagedEnvelope?: boolean;\n} {\n  const errors: ErrorResponse[] = [];\n  let response: TypeRef = undescribedBodyType();\n  let responseHeaders: ResponseHeader[] | undefined;\n  let responseContentTypes: string[] | undefined;\n  let responseContents: ResponseContent[] | undefined;\n  let responseDescription: string | undefined;\n  let inlineModels: Model[] = [];\n  let isPaginated = false;\n  let dataPath: string | undefined;\n  let dataDescription: string | undefined;\n  let itemType: TypeRef | undefined;\n  let envelopeFields: Field[] | undefined;\n  let endOfIteration: PaginationEndOfIteration | undefined;\n  let overrideItemType: TypeRef | undefined;\n  let envelopeCompanions: EnvelopeCompanion[] | undefined;\n  let unpagedEnvelope: boolean | undefined;\n\n  const allSuccessResponses: SuccessResponse[] = [];\n  const opLabel = operationLabel(op, path ?? '/', method ?? 'get');\n  // Every 2xx body's classification, by status code. The models of all of\n  // them are kept — `successResponses` references each — while the paging\n  // fields are read from the status chosen as primary once every status code\n  // has been read.\n  const bodyResults = new Map<number, ResponseExtractionResult>();\n  // The name an inline success or redirect body is materialized under\n  // (`<Op>Response`), whose stem names its secondary bodies (`RenderPetCard`\n  // + `TextHtml` + `Response`); an error entry's are named from its own\n  // `<Op>Error<code>` and a component response's from the component\n  // (`responseModelSite`).\n  const operationBodyName = deriveResponseName(op, pathModelBaseName);\n  const fallback: FallbackResponseSink = { op, pathModelBaseName, opLabel, ctx, rangeResponses: [] };\n  // Each classified body's schema, for resolving an overridden `dataPath`\n  // through the document when the IR cannot answer.\n  const bodySchemas = new Map<number, SchemaObject>();\n  // The context each 2xx body's models were named under — `<Op>Response`,\n  // or the component's shared name — the stem a later status code's body\n  // steps from when a kept model holds one of its names (`stepSecondaryBody`).\n  const bodyContexts = new Map<number, string>();\n\n  // Every 2xx, 3xx and error entry is resolved once, here, and the loop\n  // below reads it from this map. The bundler leaves `$ref:\n  // '#/components/responses/…'` in place, and a Reference Object has no\n  // `headers` or `content` of its own to read, so the ref is resolved before\n  // either is — its sibling `description` read by `ctx.refSiblingDescriptions`,\n  // an unresolvable one warned about once. Only a status code one of the\n  // branches below reads is resolved: `default`, a `2XX` range and an `x-`\n  // extension are left as written, as nothing here reads them, and a 1xx is\n  // read as written too.\n  const resolvedResponses = new Map<string, ResponseObject>();\n  for (const [statusCode, rawResponse] of Object.entries(responses ?? {})) {\n    const responseKey = classifyResponseKey(statusCode);\n    if (responseKey.kind !== 'status' || responseKey.code < 200) continue;\n    resolvedResponses.set(\n      statusCode,\n      resolveResponseRef<ResponseObject>(\n        rawResponse,\n        ctx.componentResponses,\n        `${statusCode} response of ${opLabel}`,\n        ctx.refSiblingDescriptions,\n      ),\n    );\n  }\n\n  // The override is accepted or rejected once, before any body is\n  // classified, against the primary response — the entry\n  // `Operation.response` will describe, chosen here by the one rule\n  // (`primaryResponseEntry`) — and every success body below is read with\n  // that one decision (`overrideDecision`): a rejected override is handed\n  // to no body, so a secondary 2xx is read exactly as detection reads it,\n  // never kept as the wrapper the dropped override would have selected; an\n  // accepted one applies to each body its `dataPath` reaches an array in.\n  const successEntries: SuccessEntry[] = [...resolvedResponses.entries()]\n    .map(([statusCode, resp]) => ({ code: Number(statusCode), resp }))\n    .filter(({ code }) => code < 400)\n    .map(({ code, resp }) => ({ code, pick: code < 300 ? primaryBodySchema(resp) : {} }));\n  const primaryEntry = primaryResponseEntry(successEntries, componentSchemas);\n  const overrideDecision = decidePaginationOverride(pagination, primaryEntry, operationBodyName, componentSchemas);\n  // The one reason the override cannot apply to the response, decided\n  // before any body is read. It is reported from every exit below: an\n  // operation without `responses` declares nothing an override could name\n  // either.\n  const overrideProblem = pagination.disabled ? undefined : overrideDecision.problem;\n\n  // An operation without a `responses` object declares no success response,\n  // so `response` is `unknown` here as it is for one that declares only\n  // `default`, ranges or errors.\n  if (!responses) return { response, errors, inlineModels, isPaginated, overrideProblem };\n\n  for (const [statusCode, rawResponse] of Object.entries(responses)) {\n    // The whole key decides what it names (`classifyResponseKey`): `default`\n    // and `1XX`–`5XX` are routed to their own fields, an `x-` extension is\n    // skipped, and a key OpenAPI does not define (`6XX`, `600`) is warned\n    // about and ignored. Only a three-digit 100–599 key reaches the branches\n    // below, so no digit-prefixed key is ever read as a status code.\n    const responseKey = classifyResponseKey(statusCode);\n    if (responseKey.kind !== 'status') {\n      readFallbackResponse(responseKey, statusCode, rawResponse, fallback);\n      continue;\n    }\n    const code = responseKey.code;\n    // Resolved above for every status code a branch below reads; a 1xx is\n    // read as written.\n    const resp = resolvedResponses.get(statusCode) ?? rawResponse;\n    // Set when the response came from a component: its inline body is then\n    // named after the component, shared by every operation that returns it —\n    // at a status code, as `default` or in a range (`readFallbackResponse`\n    // asks the same helper).\n    const componentModelName = code >= 200 ? sharedResponseModelName(rawResponse, ctx) : undefined;\n    // The name this entry's own inline body is materialized under: the error\n    // body's `<Op>Error<code>` for a 4xx/5xx, else `<Op>Response`.\n    const bodyName = code >= 400 ? deriveErrorModelName(op, pathModelBaseName, code) : operationBodyName;\n    // Where this response's secondary bodies and headers are named from: the\n    // component's shared body name for a `$ref` into `components/responses`,\n    // else `bodyName`.\n    const site = responseModelSite(componentModelName, bodyName, ctx);\n    // Headers belong to the status code they are declared on, success or\n    // error alike: `Location` on a 201/302, `Retry-After` on a 429. A 1xx\n    // response, which no branch below keeps, declares none worth\n    // materializing models for; a fallback response's were read above.\n    const headers = code >= 200 ? extractResponseHeaders(resp.headers, opLabel, code, ctx, site) : undefined;\n    // The response's own `description`, success or error alike. Blank text\n    // counts as absent, the way an operation's summary is read, and the key is\n    // only added when there is something to keep. A `$ref` into\n    // `components/responses` was resolved above, so the component's own\n    // `description` is read; a sibling written next to the `$ref` wins in an\n    // OAS 3.1 document and is ignored in 3.0 (`ctx.refSiblingDescriptions`).\n    const description = presentText(resp.description);\n\n    if (code >= 200 && code < 300) {\n      let extractedType: TypeRef = undescribedBodyType();\n      // The body schema to classify: the JSON one when a JSON media type is\n      // declared (`application/json` by essence, then `+json`), else — past\n      // the binary and text media types typed below without a schema — the\n      // first other media type that declares one. Either way it goes through\n      // `classifyAndExtractResponse`, so its inline models are created and\n      // the response never references a model the parser did not emit.\n      // The fixed-order pick (`primaryBodySchema`): `primaryContentType` is\n      // the media type `extractedType` is read from, as written, so its\n      // `contents` entry can share that TypeRef instead of re-deriving it.\n      const pick = primaryBodySchema(resp);\n      const bodySchema = pick.schema;\n      const primaryContentType = pick.contentType;\n      if (pick.type) extractedType = pick.type;\n      if (bodySchema) {\n        const contextName = componentModelName ?? deriveResponseName(op, pathModelBaseName);\n        // The override as decided above (`overrideDecision`): a rejected one\n        // is handed to no body, and an accepted one hands its `dataPath` to\n        // classification where it reaches an array in this body — the\n        // primary's by the decision itself, a secondary's on its own shape\n        // — so a secondary the path does not reach is read as detection\n        // reads it.\n        const dataPathOverride =\n          pagination.disabled ||\n          !overrideDecision.usable ||\n          pagination.dataPath === undefined ||\n          !resolveDataPathFromSchema(bodySchema, pagination.dataPath, contextName, componentSchemas)\n            ? undefined\n            : pagination.dataPath;\n        // When only the override can drive an iterator, a body it will not\n        // page — every body once the override is rejected, or a secondary\n        // its `dataPath` reaches no array in — keeps a list envelope as a\n        // plain response model, as under `disabled`, rather than unwrapped\n        // for an iterator that never comes.\n        const paginationDisabled =\n          pagination.disabled === true ||\n          (pagination.overrideOnly === true &&\n            (!overrideDecision.usable || (pagination.dataPath !== undefined && dataPathOverride === undefined)));\n        // The primary body's array items are settled against the registry\n        // (`typeInlineItems`); the dry run that reads a component response's\n        // names (`bodyModelNames`) passes none and mints nothing into it.\n        const result = classifyAndExtractResponse(bodySchema, contextName, componentSchemas, {\n          paginationDisabled,\n          dataPathOverride,\n          ...(ctx.registry && { settle: { registry: ctx.registry, operation: ctx.operationQualifier } }),\n        });\n        extractedType = result.response;\n        bodyResults.set(code, result);\n        bodySchemas.set(code, bodySchema);\n        bodyContexts.set(code, contextName);\n      }\n      const contents = extractResponseContents(\n        resp.content,\n        primaryContentType,\n        extractedType,\n        contentModelNaming(site, 'Response', code),\n        ctx,\n      );\n      allSuccessResponses.push({\n        statusCode: code,\n        type: extractedType,\n        ...(headers && { headers }),\n        ...(description && { description }),\n        ...contents,\n      });\n    } else if (code >= 300 && code < 400) {\n      // 3xx redirects — include so emitter can detect redirect endpoints. The\n      // type is not read from any media type, so every content entry is typed\n      // on its own.\n      const contents = extractResponseContents(\n        resp.content,\n        undefined,\n        undefined,\n        contentModelNaming(site, 'Response', code),\n        ctx,\n      );\n      allSuccessResponses.push({\n        statusCode: code,\n        type: undescribedBodyType(),\n        ...(headers && { headers }),\n        ...(description && { description }),\n        ...contents,\n      });\n    } else if (code >= 400) {\n      const json = jsonResponseSchema(resp);\n      // The entry is filled in place: an inline body is materialized under an\n      // operation-qualified name — or the component's, for a `$ref` response\n      // — once every operation has been read, and its `type` lands on this\n      // very object (`typeErrorBody`). The content entry the body was read\n      // from shares that TypeRef, so it joins the targets below.\n      const entry: ErrorResponse = { statusCode: code, type: undefined };\n      const targets: Array<{ type?: TypeRef }> = [entry];\n      const type = json\n        ? typeErrorBody(\n            json.schema,\n            componentModelName ?? bodyName,\n            code,\n            ctx,\n            targets,\n            componentModelName !== undefined,\n          )\n        : undefined;\n      entry.type = type;\n      const contents = extractResponseContents(\n        resp.content,\n        json?.contentType,\n        type,\n        contentModelNaming(site, 'Error', code),\n        ctx,\n      );\n      // An error's `type` is its JSON body by definition — `application/json`,\n      // else a `+json` media type (`jsonResponseSchema`) — so the lists are kept\n      // only when they say something `type` does not: another media type, a\n      // JSON body `type` could not be read from, or a JSON media type that is\n      // not the plain `application/json` a reader would otherwise assume. The\n      // common lone `application/json` with a schema keeps its shape.\n      const beyondType =\n        contents &&\n        (json?.contentType !== 'application/json' || contents.contents.some((content) => content.type !== type))\n          ? contents\n          : undefined;\n      if (headers) entry.headers = headers;\n      if (description) entry.description = description;\n      if (beyondType) {\n        entry.contentTypes = beyondType.contentTypes;\n        entry.contents = beyondType.contents;\n        const own = beyondType.contents.find((content) => content.contentType === json?.contentType);\n        if (own) targets.push(own);\n      }\n      errors.push(entry);\n    }\n  }\n\n  // The primary response was chosen before any body was read\n  // (`primaryResponseEntry`: the lowest 2xx with a typed body, else the\n  // lowest declared code — the rule the override was decided by), and its\n  // entry is read here: type, headers, media types, description. With no\n  // 2xx or 3xx at all, `response` stays `unknown` — the type of a body the\n  // document does not describe — with no headers, description or media\n  // types; a `2XX` range or `default` body is never promoted into it.\n  const primaryStatus = primaryEntry?.code;\n  const primary = allSuccessResponses.find((entry) => entry.statusCode === primaryStatus);\n  if (primary) {\n    response = primary.type;\n    responseHeaders = primary.headers;\n    responseContentTypes = primary.contentTypes;\n    responseContents = primary.contents;\n    // The operation-level description is the primary response's — the same\n    // entry `response` and `responseHeaders` come from.\n    responseDescription = primary.description;\n  }\n\n  // The paging fields describe `response`, so they come from the primary's\n  // body — not from whichever 2xx body happened to be read last.\n  const primaryBody = primaryStatus === undefined ? undefined : bodyResults.get(primaryStatus);\n  if (primaryBody) {\n    isPaginated = primaryBody.isPaginated;\n    dataPath = primaryBody.dataPath;\n    dataDescription = primaryBody.dataDescription;\n    itemType = primaryBody.itemType;\n    envelopeFields = primaryBody.envelopeFields;\n    endOfIteration = primaryBody.endOfIteration;\n    envelopeCompanions = primaryBody.envelopeCompanions;\n    unpagedEnvelope = primaryBody.unpagedEnvelope;\n  }\n\n  // Keep the models of every 2xx body: `successResponses` references each of\n  // them, so keeping only one body's would leave the others dangling. Every\n  // status derives the same `<Op>Response` context name, so the primary's\n  // definition — the one `response` points at — goes first; the other bodies\n  // follow in status order, and a model of theirs the kept one shares\n  // (`modelFingerprint`) resolves to the kept definition silently. A later\n  // body that reaches a model the kept ones hold under another shape is\n  // re-derived under its own stem first — `<Op>Response<code>`, then a\n  // number (`stepSecondaryBody`) — so its `successResponses` entry keeps the\n  // shape its status code declared; only a clash on a model the stem does\n  // not name is still resolved to the kept definition, with a warning. The\n  // models only a dropped copy referenced go with it (`reachedModels`): the\n  // primary's models are all read — `response`, the paging fields and their\n  // companions — while another status is read only through its\n  // `successResponses` entry, so of its models only those the entry's type\n  // still reaches are kept, rather than kept with nothing referencing them.\n  const bodiesByPrimacy = [...bodyResults.entries()].sort(([a], [b]) => {\n    if (a === primaryStatus) return -1;\n    if (b === primaryStatus) return 1;\n    return a - b;\n  });\n  const keptByName = new Map<string, { model: Model; status: number }>();\n  for (const [status, result] of bodiesByPrimacy) {\n    if (status !== primaryStatus) {\n      stepSecondaryBody(result, bodyContexts.get(status) ?? operationBodyName, status, keptByName, ctx.registry);\n    }\n    const reached =\n      status === primaryStatus ? undefined : reachedModels(result.response, result.inlineModels, keptByName);\n    for (const model of result.inlineModels) {\n      if (reached && !reached.has(model)) continue;\n      const kept = keptByName.get(model.name);\n      if (!kept) {\n        keptByName.set(model.name, { model, status });\n        inlineModels.push(model);\n      } else if (modelFingerprint(kept.model) !== modelFingerprint(model)) {\n        console.warn(\n          `[oagen] Warning: Inline model \"${model.name}\" from the ${status} response has different fields than the ${kept.status} response's — using the ${kept.status} response's`,\n        );\n      }\n    }\n  }\n\n  // An explicit `dataPath` the decision accepted names the array the\n  // iterator yields from, so its element type — not the wrapper — must\n  // become `itemType`. It is resolved against the primary body, whose models\n  // (companions included) are the ones retained above, so the item type it\n  // selects always has its model. An accepted `dataPath` reached an array in\n  // the body the decision was made against, which is this one: a body an\n  // array is reached in is typed, and the lowest typed 2xx is the primary.\n  const primarySchema = primaryStatus === undefined ? undefined : bodySchemas.get(primaryStatus);\n  if (\n    primaryStatus !== undefined &&\n    primaryBody &&\n    primarySchema &&\n    pagination.dataPath !== undefined &&\n    !pagination.disabled &&\n    overrideDecision.usable\n  ) {\n    const resolved = resolveOverrideItemType(\n      primaryBody,\n      primarySchema,\n      deriveResponseName(op, pathModelBaseName),\n      pagination.dataPath,\n      pagination.componentModels ?? [],\n      componentSchemas,\n      ctx.registry && { registry: ctx.registry, operation: ctx.operationQualifier },\n    );\n    if (resolved) {\n      overrideItemType = resolved.itemType;\n      for (const model of resolved.inlineModels) {\n        if (keptByName.has(model.name)) continue;\n        keptByName.set(model.name, { model, status: primaryStatus });\n        inlineModels.push(model);\n      }\n    }\n  }\n\n  const successResponses = allSuccessResponses.length > 1 ? allSuccessResponses : undefined;\n\n  return {\n    response,\n    responseHeaders,\n    responseContentTypes,\n    responseContents,\n    responseDescription,\n    responseStatusCode: primaryStatus,\n    successResponses,\n    errors,\n    defaultResponse: fallback.defaultResponse,\n    rangeResponses: fallback.rangeResponses.length > 0 ? fallback.rangeResponses : undefined,\n    inlineModels,\n    isPaginated,\n    dataPath,\n    dataDescription,\n    itemType,\n    envelopeFields,\n    endOfIteration,\n    overrideItemType,\n    overrideProblem,\n    envelopeCompanions,\n    unpagedEnvelope,\n  };\n}\n\n/**\n * The models of `own` — one 2xx body's — that `root`, the body's type, still\n * reaches once every name an earlier status kept resolves to that status's\n * model. A reached name's own model is in the set whatever the name's\n * fate, so a copy another status's model replaces is still compared with it\n * (and warned about when the shapes differ); the walk then continues through\n * the model the name resolves to — the kept one when there is one, since its\n * fields are what the reference reads — so a model only the replaced copy\n * referenced is not reached. A name no body minted is a component's and is\n * not followed; every own model of a name is read, so two of one name would\n * both be reached.\n */\nfunction reachedModels(root: TypeRef, own: readonly Model[], kept: ReadonlyMap<string, { model: Model }>): Set<Model> {\n  const ownByName = new Map<string, Model[]>();\n  for (const model of own) {\n    const models = ownByName.get(model.name);\n    if (models) models.push(model);\n    else ownByName.set(model.name, [model]);\n  }\n  const reached = new Set<Model>();\n  const visited = new Set<string>();\n  const queue = collectModelRefs(root);\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (visited.has(name)) continue;\n    visited.add(name);\n    const ownModels = ownByName.get(name) ?? [];\n    for (const model of ownModels) reached.add(model);\n    const resolved = kept.get(name)?.model ?? ownModels[0];\n    if (!resolved) continue;\n    for (const field of resolved.fields) queue.push(...collectModelRefs(field.type));\n  }\n  return reached;\n}\n\n/**\n * Re-derive a later status code's body under its own stem when a model it\n * reaches is already kept — by the primary, or by an earlier status code —\n * under another shape, so its `successResponses` entry keeps the shape the\n * status code declared instead of resolving to the kept model's: a 201\n * `{ owner: { id } }` beside a 200 `{ id }`, or a list envelope kept at a\n * 201 beside a 200 `{ id }` (`{ data, total_pages }`, no paging parameter).\n * The stem steps as a secondary media-type body's does (`deferredNamingStem`):\n * the status code first (`CreatePetResponse201`), then a number\n * (`CreatePetResponse2`, `…3`, …). Every model the body reaches that its\n * context names moves with it (`CreatePetResponse201Owner`) — except one a\n * kept model already holds under the same shape, which stays shared (the\n * 201's `{ owner: { id } }` beside the 200's keeps `CreatePetResponseOwner`),\n * unless it references a model that moves — the entry's type and the\n * models' fields rewritten in place, so the `contents` entry that shares\n * the type follows; a model named outside the context (a settled item,\n * `CreatePetItem`; a titled variant) keeps its name. A candidate is taken\n * when a name it would give is kept, or owned in the spec-wide registry by\n * a component or another operation, under a shape the owner does not share\n * (`ownerShares`); an identical shape shares the name, as it always did.\n * Only references the body itself minted are repointed — by identity, never\n * by name alone: an explicit `$ref` to a same-named component\n * (`isComponentModelRef`) and a reference an `allOf` merge copied from\n * another component's field (`isInheritedModelRef`) stay as written, the\n * filter the merge passes hand the same rewriters. Returns whether anything\n * moved: nothing does when no reached model clashes, or when the clash is\n * on a model the context does not name, which the caller then reports as\n * before.\n */\nfunction stepSecondaryBody(\n  result: ResponseExtractionResult,\n  context: string,\n  status: number,\n  kept: ReadonlyMap<string, { model: Model; status: number }>,\n  registry: InlineModelRegistry | undefined,\n): boolean {\n  const sharedByKept = (model: Model, name: string): boolean => {\n    const keptModel = kept.get(name)?.model;\n    return keptModel !== undefined && modelFingerprint(keptModel) === modelFingerprint(model);\n  };\n  const clashes = (model: Model, name: string): boolean => {\n    const fingerprint = modelFingerprint(model);\n    const keptModel = kept.get(name)?.model;\n    if (keptModel && modelFingerprint(keptModel) !== fingerprint) return true;\n    const owner = registry?.get(name);\n    return owner !== undefined && !ownerShares(owner, model, fingerprint);\n  };\n  // Reached through the body's own models, not the kept ones: the body\n  // keeps its root once it steps, so everything under that root is its.\n  const own = reachedModels(result.response, result.inlineModels, new Map());\n  // A model the context names carries it: as a prefix (the root, a nested\n  // object `…Owner`, a nested variant `…Shape`), as a suffix (a const-named\n  // variant, `Square…` — `deriveModelName`) or in between (a const-named\n  // nested variant, `Square…Shape`); it moves by that one occurrence. A\n  // settled item (`<Op>Item`) and a titled variant do not carry it.\n  const namedByContext = (name: string): boolean => name.includes(context);\n  const movedTo = (name: string, stem: string): string => name.replace(context, stem);\n  const named = [...own].filter((model) => namedByContext(model.name));\n  if (!named.some((model) => clashes(model, model.name))) return false;\n\n  // Only a reference the body itself minted moves with it, by the\n  // reference's identity rather than its name: an explicit `$ref` to a\n  // same-named component (`isComponentModelRef`) and a reference an `allOf`\n  // merge copied from another component's field (`isInheritedModelRef`)\n  // stay as written, so `original: { $ref: CreatePetResponseOwner }` beside\n  // an inline `owner` of that name keeps naming the component.\n  const admit = (ref: ModelRef): boolean => !isComponentModelRef(ref) && !isInheritedModelRef(ref);\n  const mintedNames = (ref: TypeRef): string[] => {\n    const found: string[] = [];\n    walkTypeRef(ref, { model: (modelRef) => void (admit(modelRef) && found.push(modelRef.name)) });\n    return found;\n  };\n  // What moves: every model the context names, except one a kept model\n  // already holds under the same shape, which stays shared — unless it\n  // references, by a minted reference, a model that moves, since its shape\n  // then differs after all.\n  const moving = new Set(named.filter((model) => !sharedByKept(model, model.name)));\n  for (let grew = true; grew;) {\n    grew = false;\n    for (const model of named) {\n      if (moving.has(model)) continue;\n      const movingNames = new Set([...moving].map((m) => m.name));\n      if (collectModelTypeRefs(model).some((ref) => mintedNames(ref).some((name) => movingNames.has(name)))) {\n        moving.add(model);\n        grew = true;\n      }\n    }\n  }\n  const under = (stem: string): Map<Model, string> =>\n    new Map([...moving].map((model) => [model, movedTo(model.name, stem)]));\n  let names = under(`${context}${status}`);\n  // Unbounded on purpose: the kept names and the registry are finite and\n  // every step is a new number, so a free stem is always reached.\n  for (let n = 2; [...names].some(([model, name]) => clashes(model, name)); n++) names = under(`${context}${n}`);\n\n  // Every reference moves through the one rewriter every rename site uses\n  // (`renameTypeRefModels`, `renameModelRefs`), under the identity filter\n  // above, so a union's `discriminator.mapping` follows the variant it\n  // belongs to and never keeps naming the model that moved, and a `$ref`\n  // left in place keeps its mapping entry.\n  const byOldName = new Map([...names].map(([model, name]) => [model.name, name]));\n  renameTypeRefModels(result.response, byOldName, admit);\n  for (const model of own) renameModelRefs(model, byOldName, admit);\n  for (const [model, name] of names) model.name = name;\n  return true;\n}\n\n/**\n * Shared with the inline-model merge passes, which decide whether two\n * same-named inline models are the same shape but for `deprecated` by it.\n */\nexport { modelFingerprint };\n","import { createHash } from 'node:crypto';\nimport type {\n  Enum,\n  HttpMethod,\n  Model,\n  Parameter,\n  RequestBodyContent,\n  Service,\n  TypeRef,\n  Webhook,\n  WebhookResponse,\n} from '../ir/types.js';\nimport { collectModelTypeRefs, collectOperationTypeRefs, collectWebhookTypeRefs, walkTypeRef } from '../ir/types.js';\nimport { foldParameterName, parameterKey } from '../ir/parameter-key.js';\nimport { toPascalCase } from '../utils/naming.js';\nimport { mediaTypeNameFragment } from '../utils/media-type.js';\nimport type { SchemaObject } from './schemas.js';\nimport { isComponentModelRef, schemaToTypeRef } from './schemas.js';\nimport {\n  cloneTypeRef,\n  extractInlineModelsFromProperties,\n  modelFingerprint,\n  qualifyInlineModelName,\n  type InlineModelBundle,\n} from './inline-models.js';\nimport {\n  HTTP_METHODS,\n  extractParams,\n  extractTags,\n  operationIdModelBase,\n  parameterSchema,\n  presentText,\n  requestBodyDescriptionOf,\n  resolveOperationDocs,\n  resolveParameterRef,\n  resolveRequestBodyRef,\n  schemalessRequestBodyType,\n  schemalessRequestContentType,\n  selectRequestBodyContent,\n  warnUnreadParameterContent,\n  warnUnreadRequestBody,\n  type OperationObject,\n  type ParameterObject,\n  type PathItem,\n  type RequestBodyObject,\n} from './operations.js';\nimport { externalDocsEntry } from './external-docs.js';\nimport { resolvePathItemRef } from './path-item-refs.js';\nimport { followReference, type SiblingDocs } from './reference-objects.js';\nimport { classifyResponseKey, warnUnrecognizedResponseKey } from './responses.js';\nimport { extractSecurityRequirements } from './security.js';\nimport { warnOnIgnoredCallbacks } from './callbacks.js';\n\n/** The `components` sections webhook extraction resolves references against. */\nexport interface WebhookComponents {\n  schemas?: Record<string, SchemaObject>;\n  parameters?: Record<string, Record<string, unknown>>;\n  requestBodies?: Record<string, Record<string, unknown>>;\n  responses?: Record<string, Record<string, unknown>>;\n  examples?: Record<string, Record<string, unknown>>;\n  /** `components.pathItems` (OpenAPI 3.1), the only target a webhook entry's `$ref` may point at. */\n  pathItems?: Record<string, Record<string, unknown>>;\n}\n\nexport interface WebhookExtractionResult {\n  /** One entry per (webhook key, HTTP method), in document order. */\n  webhooks: Webhook[];\n  /** Models materialized from inline payload and parameter schemas, to merge into `ApiSpec.models`. */\n  inlineModels: Model[];\n  /**\n   * Where those models came from: one site per group of entries that share\n   * a minting, qualified by the group's stem and owning every reference of\n   * every webhook in the group — its payload and its parameters\n   * (`collectWebhookTypeRefs`) — so a merge pass that must rename one of the\n   * models (a payload variant titled like a component of another shape)\n   * repoints exactly those, as it does an operation's (`InlineModelBundle`).\n   */\n  inlineModelBundles: InlineModelBundle[];\n}\n\n/** One (key, method) pair of the `webhooks` map, with its references resolved. */\ninterface WebhookEntry {\n  name: string;\n  method: HttpMethod;\n  op: OperationObject;\n  /**\n   * The path item the operation sits on — the entry itself, or the\n   * `components/pathItems` item its `$ref` leads to — whose `summary` and\n   * `description` apply to the operation (`resolveOperationDocs`).\n   */\n  pathItem: PathItem;\n  /** The webhook's own parameters after path-item-level ones, deduplicated by (in, name). */\n  params: ParameterObject[];\n  body: RequestBodyObject | undefined;\n  /** `webhooks.<name>.<method>`, for diagnostics. */\n  label: string;\n  /** How many methods the entry's path item declares; a second one qualifies a key-derived stem. */\n  methodCount: number;\n  /**\n   * The operationId the stem is named from: the operation's own, unless a\n   * different operation object declares the same one (see\n   * `collectWebhookEntries`). Absent, the stem comes from the key.\n   */\n  stemOperationId?: string;\n}\n\n/** What one stem mints for a webhook: its typed parameters and payload, and the models behind them. */\ninterface MintedWebhook {\n  headerParams: Parameter[];\n  queryParams: Parameter[];\n  cookieParams: Parameter[];\n  requestBody?: TypeRef;\n  requestBodyEncoding?: Webhook['requestBodyEncoding'];\n  requestBodyContentType?: string;\n  requestBodyContentTypes?: string[];\n  requestBodyContents?: RequestBodyContent[];\n  inlineModels: Model[];\n  /** Every model and inline-enum name the webhook minted (see `mintSchema`). */\n  names: Set<string>;\n}\n\n/** The part of a minting a `Webhook` carries: its typed parameters and payload. */\ntype MintedShape = Pick<\n  MintedWebhook,\n  | 'headerParams'\n  | 'queryParams'\n  | 'cookieParams'\n  | 'requestBody'\n  | 'requestBodyEncoding'\n  | 'requestBodyContentType'\n  | 'requestBodyContentTypes'\n  | 'requestBodyContents'\n>;\n\n/**\n * Read the document's top-level `webhooks` map (OpenAPI 3.1) into the IR.\n *\n * Each key names a path item, and each HTTP method on it is one `Webhook`,\n * in document order. The key is kept verbatim as `Webhook.name`. An entry\n * that is a `$ref` into `components/pathItems` is resolved (chains included,\n * with a cycle guard) by `resolvePathItemRef`, the resolver a `paths` entry\n * goes through too; one that points anywhere else, or that cannot be\n * resolved, is warned about and skipped rather than failing the parse, as is\n * an entry that is not an object. A key starting with `x-` is a\n * specification extension, not a webhook, and is stepped over without a\n * warning whatever its value, as `extractOperations` steps over one under\n * `paths`. A `webhooks` value that is not an object at all is warned about\n * and ignored. Nothing is read from `x-webhooks`, the\n * pre-3.1 convention: the parser reads the standard key only.\n *\n * Parameters and request bodies go through the same resolvers and extractors\n * as operations (`components/parameters` and `components/requestBodies` refs\n * resolved, path-item-level parameters overridden by operation-level ones of\n * the same identity), so a malformed reference fails the parse the way it\n * does on an operation. A `path` parameter has nowhere to go — a webhook has\n * no path — and is dropped with a warning. A response that is a `$ref` into\n * `components/responses` is followed for its description.\n *\n * The payload schema is typed and materialized as the `payload` property of a\n * synthetic object named by the webhook's stem (see\n * `resolveWebhookModelStems`), through the same `schemaToTypeRef` /\n * `extractInlineModelsFromProperties` pair that names component fields and\n * response unions. An inline object therefore becomes `<Stem>Payload` with\n * its nested objects under it (`<Stem>PayloadPet`); a `oneOf` of inline\n * objects stays a union whose variants are named as any field-level union's\n * are, discriminator intact, because an event handler switches on it; a\n * `$ref` stays a reference; an inline enum takes the same name and is\n * promoted by `collectInlineEnumsFromWebhooks`. Nothing is flattened. An\n * inline object on a parameter is materialized the same way, under the name\n * `extractParams` references it by (`<Stem>XMeta`).\n *\n * `reservedNames` is every model and enum name already decided — see\n * `collectExistingNames` — so a webhook never mints a name one of them owns,\n * and `reservedEnumNames` the enums among them (`collectExistingEnumNames`),\n * which no webhook model may take even where the stem cannot move it.\n */\nexport function extractWebhooks(\n  webhooks: unknown,\n  components: WebhookComponents = {},\n  reservedNames: Iterable<string> = [],\n  reservedEnumNames: Iterable<string> = [],\n  // Whether text written beside a `$ref` into `components/parameters`,\n  // `requestBodies`, `responses` or `examples` overrides the component's\n  // (OAS 3.1) or is ignored (OAS 3.0): the document's mode, as the operations\n  // read it (`siblingDocsMode`), applied to every Reference Object here.\n  siblingDocs: SiblingDocs = 'override',\n): WebhookExtractionResult {\n  if (webhooks === undefined) return { webhooks: [], inlineModels: [], inlineModelBundles: [] };\n  if (!isRecord(webhooks)) {\n    console.warn('[oagen] Warning: Top-level `webhooks` is not an object; ignoring it.');\n    return { webhooks: [], inlineModels: [], inlineModelBundles: [] };\n  }\n\n  const entries = collectWebhookEntries(webhooks, components, siblingDocs);\n  const { groups, groupOf } = groupEntries(entries);\n  const reserved: ReservedNames = { all: new Set(reservedNames), enums: new Set(reservedEnumNames) };\n  const stems = resolveWebhookModelStems(groups, reserved, components, siblingDocs);\n  const inlineModels: Model[] = [];\n  const mintedByGroup = new Map<WebhookGroup, MintedWebhook>();\n  for (const group of groups) {\n    const minted = mintWebhook(group.owner, stems.get(group)!, components, reserved, siblingDocs);\n    inlineModels.push(...minted.inlineModels);\n    mintedByGroup.set(group, minted);\n  }\n\n  // Document order of the entries, not of the groups: a shared operation's\n  // second key keeps its own place. A group's owner takes the minted\n  // parameters and payload as they are; every other member gets its own\n  // copy, so no two webhooks share IR nodes — a copy that keeps each\n  // reference's provenance (`cloneMintedShape`), so a `$ref` to a component\n  // stays one on every member when a merge pass renames the group's models.\n  const result: Webhook[] = [];\n  const webhooksByGroup = new Map<WebhookGroup, Webhook[]>();\n  for (const entry of entries) {\n    const group = groupOf.get(entry)!;\n    const minted = mintedByGroup.get(group)!;\n    const shape: MintedShape = {\n      headerParams: minted.headerParams,\n      queryParams: minted.queryParams,\n      cookieParams: minted.cookieParams,\n      requestBody: minted.requestBody,\n      requestBodyEncoding: minted.requestBodyEncoding,\n      requestBodyContentType: minted.requestBodyContentType,\n      requestBodyContentTypes: minted.requestBodyContentTypes,\n      requestBodyContents: minted.requestBodyContents,\n    };\n    const webhook = buildWebhook(\n      entry,\n      entry === group.owner ? shape : cloneMintedShape(shape),\n      components,\n      siblingDocs,\n    );\n    result.push(webhook);\n    webhooksByGroup.set(group, [...(webhooksByGroup.get(group) ?? []), webhook]);\n  }\n\n  // Each group's models are one site: every member's references, the\n  // copies included, so a rename reaches every webhook that shares the\n  // minting and nothing else.\n  const inlineModelBundles: InlineModelBundle[] = [];\n  for (const group of groups) {\n    const minted = mintedByGroup.get(group)!;\n    if (minted.inlineModels.length === 0) continue;\n    inlineModelBundles.push({\n      qualifier: toPascalCase(stems.get(group)!),\n      roots: (webhooksByGroup.get(group) ?? []).flatMap((webhook) => collectWebhookTypeRefs(webhook)),\n      models: minted.inlineModels,\n    });\n  }\n\n  return { webhooks: result, inlineModels, inlineModelBundles };\n}\n\n/**\n * Every model and enum name the rest of the parse has decided before webhooks\n * are extracted, for `extractWebhooks` to reserve: each model's name, each\n * enum's name, and every model or enum a model field or an operation refers\n * to (parameters, bodies, responses, errors, pagination envelopes, response\n * headers), inline enums included since their names are already fixed in the\n * references that carry them. A superset is harmless — a referenced name is\n * one that exists — and keeps the check from depending on which pass minted\n * what.\n */\nexport function collectExistingNames(models: Model[], services: Service[], enums: Enum[]): Set<string> {\n  return collectExistingNamesByKind(models, services, enums).all;\n}\n\n/**\n * The enum names among `collectExistingNames`: each enum's name, and every\n * enum a model field or an operation refers to, inline enums included. A\n * webhook model may never take one of these (`mintSchema`): a model and an\n * enum under one name would reach an emitter as one public symbol.\n */\nexport function collectExistingEnumNames(models: Model[], services: Service[], enums: Enum[]): Set<string> {\n  return collectExistingNamesByKind(models, services, enums).enums;\n}\n\n/** The names a webhook's minting must step around: every decided name, and among them the enums'. */\ninterface ReservedNames {\n  all: ReadonlySet<string>;\n  enums: ReadonlySet<string>;\n}\n\nfunction collectExistingNamesByKind(\n  models: Model[],\n  services: Service[],\n  enums: Enum[],\n): { all: Set<string>; enums: Set<string> } {\n  const names = new Set<string>();\n  const enumNames = new Set<string>();\n  const collect = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      model: (r) => names.add(r.name),\n      enum: (r) => {\n        names.add(r.name);\n        enumNames.add(r.name);\n      },\n    });\n  };\n  for (const model of models) {\n    names.add(model.name);\n    for (const field of model.fields) collect(field.type);\n  }\n  for (const e of enums) {\n    names.add(e.name);\n    enumNames.add(e.name);\n  }\n  for (const service of services) {\n    for (const op of service.operations) for (const ref of collectOperationTypeRefs(op)) collect(ref);\n  }\n  return { all: names, enums: enumNames };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Flatten the map into one entry per (key, method), resolving path-item refs\n * and parameter / request-body refs up front so the stem resolution below can\n * mint every entry's names before any stem is decided.\n */\nfunction collectWebhookEntries(\n  webhooks: Record<string, unknown>,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n): WebhookEntry[] {\n  const entries: WebhookEntry[] = [];\n  for (const [name, raw] of Object.entries(webhooks)) {\n    // A specification extension, never a webhook: stepped over whatever its\n    // value, as `resolvePathItems` steps over one under `paths`.\n    if (name.startsWith('x-')) continue;\n    // The same resolver `extractOperations` reads a `paths` entry through, so\n    // a `$ref` into `components/pathItems` is followed the same way here.\n    const pathItem = resolvePathItemRef(raw, components.pathItems, { kind: 'webhook', key: name }) as\n      | PathItem\n      | undefined;\n    if (!pathItem) continue;\n    // The path item's own key order, as the IR promises document order; an\n    // entry declaring `put` before `post` keeps `put` first.\n    const methods = (Object.keys(pathItem) as string[]).filter(\n      (key): key is HttpMethod =>\n        (HTTP_METHODS as readonly string[]).includes(key) && isRecord(pathItem[key as HttpMethod]),\n    );\n    for (const method of methods) {\n      const op = pathItem[method] as OperationObject;\n      const label = `webhooks.${name}.${method}`;\n      warnOnIgnoredCallbacks(op.callbacks, label);\n      // Same precedence as buildOperation: an operation-level parameter replaces\n      // a path-item-level one of the same identity (`parameterKey`: location\n      // and name, a header's name case-folded), in the path-level position.\n      const paramsByIdentity = new Map<string, ParameterObject>();\n      for (const rawParam of [...(pathItem.parameters ?? []), ...(op.parameters ?? [])]) {\n        const param = resolveParameterRef(rawParam, components.parameters, label, siblingDocs);\n        paramsByIdentity.set(parameterKey(param.in, param.name), param);\n      }\n      const params: ParameterObject[] = [];\n      for (const param of paramsByIdentity.values()) {\n        if (param.in === 'path') {\n          console.warn(\n            `[oagen] Warning: Parameter \"${param.name}\" (in: path) on ${label} ignored: a webhook has no path to place it in.`,\n          );\n          continue;\n        }\n        // Reported here, once per webhook parameter: the mint below runs\n        // twice for each webhook, so it must not report.\n        warnUnreadParameterContent(param, `Parameter \"${param.name}\" (in: ${param.in}) on ${label}`);\n        params.push(param);\n      }\n      const body = resolveRequestBodyRef(op.requestBody, components.requestBodies, label, siblingDocs);\n      // Reported here, once per webhook: the mint below runs twice for each\n      // (`resolveWebhookModelStems`, then the build), so it must not report.\n      warnUnreadRequestBody(body, label);\n      entries.push({ name, method, op, pathItem, params, body, label, methodCount: methods.length });\n    }\n  }\n\n  // An operationId names the stem only when exactly one operation object\n  // declares it. Two keys that `$ref` one path item resolve to the same\n  // object and are fine — they will share a stem (see `groupEntries`); two\n  // different objects declaring one id is a document error OpenAPI forbids,\n  // so neither is named from it, with a warning.\n  const objectsByOperationId = new Map<string, Set<OperationObject>>();\n  for (const entry of entries) {\n    const id = entry.op.operationId;\n    if (typeof id !== 'string' || id === '') continue;\n    const objects = objectsByOperationId.get(id) ?? new Set<OperationObject>();\n    objects.add(entry.op);\n    objectsByOperationId.set(id, objects);\n  }\n  for (const [id, objects] of objectsByOperationId) {\n    const declaring = entries.filter((entry) => entry.op.operationId === id);\n    if (objects.size === 1) {\n      for (const entry of declaring) entry.stemOperationId = id;\n      continue;\n    }\n    console.warn(\n      `[oagen] Warning: operationId \"${id}\" is declared by more than one webhook operation ` +\n        `(${declaring.map((entry) => entry.label).join(', ')}); naming their models from the webhook keys instead.`,\n    );\n  }\n  return entries;\n}\n\n/**\n * Decide the stem every model of each webhook is named from: `<Stem>Payload`\n * for the payload, `<Stem>Payload<Field>` for objects nested in it,\n * `<Const><Stem>Payload` for a const-discriminated variant, `<Stem><Param>`\n * for an inline parameter object or enum.\n *\n * The plain stem is the `operationId` when the operation declares one — run\n * through the same cleaning an operation's own `…Request` model gets, so a\n * webhook and an operation with the same id name their models alike — and\n * the PascalCase of the webhook's key otherwise. When a key's path item\n * declares several methods, a key-derived stem has the method appended\n * (`PetUpdatedPut`) so the bodies never share a model. An operationId is\n * unique per document and needs no qualifier, with one caveat: two keys that\n * `$ref` the same `components/pathItems` entry resolve to one operation\n * object and so carry one operationId. Sharing a path item between events is\n * what that section is for, so such entries form one group (`groupEntries`)\n * that mints once and shares its stem and its models (`SharedPayload`)\n * rather than colliding with each other; each key is still its own\n * `Webhook`. An operationId that two different operation objects declare —\n * which no valid document does — is ignored for naming, with a warning, and\n * those webhooks take their key-derived stems (`collectWebhookEntries`). A\n * key that PascalCases to nothing, or to something starting with a digit,\n * gets `Webhook` in front.\n *\n * Whether a stem collides is decided from the names it actually mints, not\n * from a prefix: every group is first minted with its plain stem\n * (`mintWebhook`) and the model and inline-enum names that produces —\n * payload, nested objects, union variants with their const or title\n * prefixes, parameter objects, parameter enums, field enums — are collected\n * (`MintedWebhook.names`). A group collides when one of those names is\n * reserved (`collectExistingNames`: every model and enum the components and\n * the operations have decided, the components' own inline field models\n * included) or is also minted by another group. Two keys that flatten to\n * one stem (`pet_adopted` and `petAdopted`) collide on every name; a\n * `petEvent` union variant pinning `kind: returned` and a webhook keyed\n * `returnedPetEvent` collide on the one name `ReturnedPetEventPayload`; a\n * stem that merely starts with another's (`petAdopted` beside\n * `petAdoptedPayloadPet`) does not collide unless a name coincides. A\n * colliding stem takes the first six hex characters of the SHA-1 of the\n * webhook's operationId when it is named from one and of its key otherwise,\n * before the method qualifier (`PetAdoptedB4A950`), exactly as an\n * operationId-less operation's path prefix does, and is minted again under\n * it. Both sides of a webhook-to-webhook collision are hashed, since neither\n * key is more canonical than the other. The outcome depends only on the\n * document's keys, operationIds, components and operations, never on their\n * order, and a key that stops colliding returns to its plain stem.\n *\n * A name that does not embed the stem — a title-mapped union variant, which\n * is context-free by design — cannot be moved by the hash, so a clash on it\n * alone leaves the stem plain. One named like a decided enum is renamed\n * under the payload's root instead (`PetAdoptedPayloadCircle`, see\n * `mintSchema`), since a model and an enum under one name would reach an\n * emitter as one symbol; one named like a decided model, or like another\n * webhook's variant, is left to the model merge, which shares a component's\n * name when the component admits the shape and renames the variant under\n * the webhook's stem otherwise (`PetAdoptedComp`), as it does for\n * operations.\n */\nfunction resolveWebhookModelStems(\n  groups: WebhookGroup[],\n  reserved: ReservedNames,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n): Map<WebhookGroup, string> {\n  const minted = new Map<WebhookGroup, Set<string>>();\n  for (const group of groups) {\n    minted.set(group, mintWebhook(group.owner, plainStem(group.owner, ''), components, reserved, siblingDocs).names);\n  }\n\n  const stems = new Map<WebhookGroup, string>();\n  for (const group of groups) {\n    const names = minted.get(group)!;\n    const { owner } = group;\n    // Only a clashing name the hash would move — one that embeds the stem —\n    // moves the stem.\n    const stem = toPascalCase(plainStem(owner, ''));\n    const taken = [...names].some(\n      (name) =>\n        name.includes(stem) &&\n        (reserved.all.has(name) || groups.some((other) => other !== group && minted.get(other)!.has(name))),\n    );\n    const disambiguator = taken ? webhookDisambiguator(owner.stemOperationId ?? owner.name) : '';\n    stems.set(group, plainStem(owner, disambiguator));\n  }\n  return stems;\n}\n\n/**\n * Entries that mint together. Those resolving to one operation object and\n * named from its operationId share a group: `owner` is the first of them in\n * document order, and its parameters and body stand for the group's, since\n * every member read the same path item. Every other entry is a group of its\n * own.\n */\ninterface WebhookGroup {\n  owner: WebhookEntry;\n  entries: WebhookEntry[];\n}\n\nfunction groupEntries(entries: WebhookEntry[]): { groups: WebhookGroup[]; groupOf: Map<WebhookEntry, WebhookGroup> } {\n  const groups: WebhookGroup[] = [];\n  const groupOf = new Map<WebhookEntry, WebhookGroup>();\n  const byOperation = new Map<OperationObject, WebhookGroup>();\n  for (const entry of entries) {\n    const shared = entry.stemOperationId !== undefined;\n    let group = shared ? byOperation.get(entry.op) : undefined;\n    if (!group) {\n      group = { owner: entry, entries: [] };\n      groups.push(group);\n      if (shared) byOperation.set(entry.op, group);\n    }\n    group.entries.push(entry);\n    groupOf.set(entry, group);\n  }\n  return { groups, groupOf };\n}\n\n/** The stem of `entry` with `disambiguator` (possibly empty) inserted before the method qualifier. */\nfunction plainStem(entry: WebhookEntry, disambiguator: string): string {\n  const operationId = entry.stemOperationId;\n  const method = !operationId && entry.methodCount > 1 ? entry.method : '';\n  const base = operationId ? operationIdModelBase(operationId) : toPascalCase(entry.name);\n  // `_` separators guarantee a word boundary on each side of the disambiguator\n  // and the method, whatever the base ends with; splitWords drops them.\n  const stem = toPascalCase([base, disambiguator, method].filter(Boolean).join('_'));\n  if (stem === '') return 'Webhook';\n  return /^\\d/.test(stem) ? `Webhook${stem}` : stem;\n}\n\n/** The first six hex characters of the SHA-1 of a webhook's key. */\nfunction webhookDisambiguator(name: string): string {\n  return createHash('sha1').update(name).digest('hex').slice(0, 6);\n}\n\n/**\n * Type a webhook's parameters and payload under `stem`, materializing every\n * model they reference inline, in one namespace per webhook.\n *\n * The payload goes first, as the synthetic `payload` property of the stem\n * (`<Stem>Payload`, nested objects under it), through the same\n * `schemaToTypeRef` / `extractInlineModelsFromProperties` pair that names\n * component fields and response unions, so for every shape the field\n * extractor knows — an inline object, a `oneOf`/`anyOf` of inline objects, an\n * `allOf` merge or `$ref` augmentation, an array or map of any of those, an\n * inline enum, a nullable wrapper — the reference and the model are named by\n * one code path. A body with no schema is a binary or text primitive, as on\n * an operation.\n *\n * Each parameter then goes through `extractParams` with the stem as the\n * qualifying context, as a service name qualifies an operation's\n * (`PetAdopted` + `X-Event-Type` → `PetAdoptedXEventType`), and one whose\n * schema mints anything inline — an object, an array of them, an enum — is\n * run through the field extractor as a single synthetic property of the\n * stem, which names the model exactly as `extractParams` referenced it, the\n * pairing response headers already rely on. The property is the parameter's\n * own name unless a name it would mint is already taken by the payload or an\n * earlier parameter of this webhook: a query parameter named `payload` would\n * mint the body's `<Stem>Payload`, one named `payload_pet` the body's nested\n * `<Stem>PayloadPet`, and a header `X-Meta` beside a query `x_meta` would\n * mint `<Stem>XMeta` twice. Such a parameter is typed and minted under its\n * location-qualified name instead (`query_payload` → `<Stem>QueryPayload`),\n * then a numbered one (`<Stem>QueryPayload2`, …), the first that takes\n * nothing already minted, and its reference follows (see `mintParameter`).\n * Parameters are visited in document order, so the outcome depends only on\n * the document. `names` carries everything the webhook minted, for the stem\n * decision in `resolveWebhookModelStems`.\n */\nfunction mintWebhook(\n  entry: WebhookEntry,\n  stem: string,\n  components: WebhookComponents,\n  reserved: ReservedNames,\n  siblingDocs: SiblingDocs,\n): MintedWebhook {\n  const { params, body, label } = entry;\n  const parent = toPascalCase(stem);\n  const inlineModels: Model[] = [];\n  const names = new Set<string>();\n  const extract = (location: 'query' | 'header' | 'cookie'): Parameter[] =>\n    extractParams(params, location, stem, components.schemas, components.examples, label, siblingDocs);\n  const minted: MintedWebhook = {\n    headerParams: extract('header'),\n    queryParams: extract('query'),\n    cookieParams: extract('cookie'),\n    inlineModels,\n    names,\n  };\n\n  const payload = mintPayload(body, stem, components.schemas, reserved);\n  if (payload) {\n    minted.requestBody = payload.ref;\n    minted.requestBodyEncoding = payload.encoding;\n    minted.requestBodyContentType = payload.contentType;\n    minted.requestBodyContentTypes = payload.contentTypes;\n    minted.requestBodyContents = payload.contents;\n    inlineModels.push(...payload.models);\n    for (const name of payload.names) names.add(name);\n  }\n\n  // Each raw parameter and the IR parameter `extractParams` typed from it,\n  // paired on the identity every parameter lookup uses (`parameterKey`).\n  const typed = new Map<string, Parameter>();\n  for (const [location, list] of [\n    ['header', minted.headerParams],\n    ['query', minted.queryParams],\n    ['cookie', minted.cookieParams],\n  ] as const) {\n    for (const param of list) typed.set(parameterKey(location, param.name), param);\n  }\n  for (const param of params) {\n    const ir = typed.get(parameterKey(param.in, param.name));\n    // The schema `extractParams` typed the parameter from: `schema`, else\n    // the picked `content` entry's (`parameterTyping`).\n    const schema = parameterSchema(param);\n    if (!ir || !schema) continue;\n    const { ref, models, names: own } = mintParameter(param, schema, parent, names, components.schemas, reserved);\n    // `extractParams` typed the parameter from its schema alone; the minted\n    // reference is the one whose models exist — it differs when the parameter\n    // moved to a qualified property, and when a variant was renamed past a\n    // decided enum (`mintSchema`) under the parameter's own name — so it\n    // always replaces the extracted type, variants and discriminator mapping\n    // included, whether or not the property name changed.\n    ir.type = ref;\n    inlineModels.push(...models);\n    for (const name of own) names.add(name);\n  }\n  return minted;\n}\n\n/**\n * A copy of a minted shape for a second member of a group, carrying every\n * field the shape has: the fields that hold type references — the\n * parameters, the payload, the content entries — are copied through\n * `cloneTypeRef`, so each reference keeps the marks the merge passes read (a\n * `$ref` to a component, an inherited reference, an inline enum's members),\n * and each reference is cloned once, so a content entry whose `type` is the\n * payload's own reference shares the copy as it shared the original; every\n * other field (the encoding, the content type and its list, anything added\n * to the shape later) is copied structurally, present or absent exactly as\n * on the original. A field that comes to hold a type reference must join the\n * first group.\n */\nfunction cloneMintedShape(shape: MintedShape): MintedShape {\n  const clones = new Map<TypeRef, TypeRef>();\n  const clone = (ref: TypeRef): TypeRef => {\n    let copy = clones.get(ref);\n    if (!copy) clones.set(ref, (copy = cloneTypeRef(ref)));\n    return copy;\n  };\n  const cloneParameter = ({ type, ...rest }: Parameter): Parameter => ({ ...structuredClone(rest), type: clone(type) });\n  const { headerParams, queryParams, cookieParams, requestBody, requestBodyContents, ...rest } = shape;\n  return {\n    ...structuredClone(rest),\n    headerParams: headerParams.map(cloneParameter),\n    queryParams: queryParams.map(cloneParameter),\n    cookieParams: cookieParams.map(cloneParameter),\n    ...(requestBody ? { requestBody: clone(requestBody) } : {}),\n    ...(requestBodyContents\n      ? {\n          requestBodyContents: requestBodyContents.map(({ type, ...entry }) => ({\n            ...structuredClone(entry),\n            type: clone(type),\n          })),\n        }\n      : {}),\n  };\n}\n\n/** What one schema minted under one synthetic property: its reference, its models, and every name among them. */\ninterface MintedSchema {\n  ref: TypeRef;\n  models: Model[];\n  names: Set<string>;\n}\n\n/** What a webhook's body mints: the picked payload's reference and encoding, every media type with its type, and the models behind them. */\ninterface MintedPayload {\n  /** The picked entry's type (`Webhook.requestBody`); absent when no media type is read. */\n  ref?: TypeRef;\n  encoding?: Webhook['requestBodyEncoding'];\n  /** The picked entry's essence (`Webhook.requestBodyContentType`); set exactly when `ref` is. */\n  contentType?: string;\n  contentTypes: string[];\n  contents: RequestBodyContent[];\n  models: Model[];\n  names: Set<string>;\n}\n\n/**\n * The payload typed and materialized as the `payload` property of `stem`,\n * read from the content entry the operation body pick chooses\n * (`selectRequestBodyContent`, by media type essence), plus one entry per\n * media type the body declares, as `Operation.requestBodyContents` carries\n * them: the picked entry shares `ref`; every other entry with a schema is\n * typed and materialized as the `<MediaType>Payload` property of the stem\n * (`PetAdoptedTextCsvPayload`, named the way the body's own\n * `<Stem>Payload` is), and one without is typed as\n * `schemalessRequestContentType` types it. `undefined` when the body\n * declares no media type at all. A body none of whose media types is read\n * as `ref` is reported where the webhook's entry is built\n * (`warnUnreadRequestBody`), not here: the mint runs twice per webhook and\n * the warning fires once.\n */\nfunction mintPayload(\n  body: RequestBodyObject | undefined,\n  stem: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedPayload | undefined {\n  const content = body?.content;\n  if (!content) return undefined;\n  const contentTypes = Object.keys(content);\n  if (contentTypes.length === 0) return undefined;\n  const minted: MintedPayload = { contentTypes, contents: [], models: [], names: new Set() };\n  const absorb = ({ ref, models, names }: MintedSchema): TypeRef => {\n    minted.models.push(...models);\n    for (const name of names) minted.names.add(name);\n    return ref;\n  };\n\n  const selected = selectRequestBodyContent(body);\n  if (selected) {\n    minted.encoding = selected.encoding;\n    minted.contentType = selected.essence;\n    // Only a binary or text pick comes without a schema; it is a primitive.\n    minted.ref = selected.schema\n      ? absorb(mintSchema(selected.schema, 'payload', stem, componentSchemas, reserved))\n      : schemalessRequestBodyType(selected.encoding);\n  }\n  for (const contentType of contentTypes) {\n    const schema = content[contentType]?.schema;\n    const type =\n      selected && contentType === selected.contentType && minted.ref\n        ? minted.ref\n        : schema\n          ? absorb(mintSecondaryPayload(schema, contentType, contentTypes, stem, minted, componentSchemas, reserved))\n          : schemalessRequestContentType(contentType);\n    minted.contents.push({ contentType, type });\n  }\n  return minted;\n}\n\n/**\n * A secondary payload entry typed and materialized under the first\n * `<Fragment>Payload` property whose minted names are free of everything the\n * payload has minted so far — `<Fragment>Payload`, then `<Fragment>Payload2`,\n * `…Payload3`, … — the fragment coming from the media type's essence and,\n * when another key of the same essence sits beside it, its parameters\n * (`mediaTypeNameFragment`), so `application/xml` and `APPLICATION/XML;\n * charset=utf-8` take `…ApplicationXmlPayload` and\n * `…ApplicationXmlCharsetUtf8Payload` before any candidate is tried. A\n * candidate whose names are all taken by models of the very shape this entry\n * mints shares them and mints nothing, as the operation registry shares an\n * identical shape; a name taken by a different shape (`application/xml` and\n * `APPLICATION/XML` with other fields) steps on, so no two entries of one\n * payload ever point at a model with the other's fields. When a candidate\n * changes none of the clashing names (a title-mapped variant, which embeds\n * no property), no candidate can clear them: the earliest trial is kept,\n * under `<Fragment>Payload`, and the clash left to the model merge, as\n * `mintParameter` does.\n */\nfunction mintSecondaryPayload(\n  schema: SchemaObject,\n  contentType: string,\n  siblings: readonly string[],\n  stem: string,\n  minted: MintedPayload,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedSchema {\n  const fragment = mediaTypeNameFragment(contentType, siblings);\n  const own = new Map(minted.models.map((model) => [model.name, model]));\n  let previous: { trial: MintedSchema; clashing: string } | undefined;\n  for (let attempt = 0; ; attempt++) {\n    const property = attempt === 0 ? `${fragment}Payload` : `${fragment}Payload${attempt + 1}`;\n    const trial = mintSchema(schema, property, stem, componentSchemas, reserved);\n    const taken = [...trial.names].filter((name) => minted.names.has(name));\n    if (taken.length === 0) return trial;\n    const sharesShape =\n      taken.length === trial.names.size &&\n      trial.models.every((model) => {\n        const owner = own.get(model.name);\n        return owner !== undefined && modelFingerprint(owner) === modelFingerprint(model);\n      });\n    if (sharesShape) return { ref: trial.ref, models: [], names: new Set() };\n    // Judged on the clashing names alone: a name that embeds the property (a\n    // variant renamed past a decided enum) changes with every candidate.\n    const clashing = taken.sort().join('\\n');\n    if (previous !== undefined && previous.clashing === clashing) return previous.trial;\n    if (attempt >= MAX_PARAMETER_PROPERTY_ATTEMPTS) return trial;\n    previous = { trial, clashing };\n  }\n}\n\n/**\n * A parameter's schema typed and materialized under the first synthetic\n * property whose minted names are all free: the parameter's own name, then\n * `<in>_<name>`, then `<in>_<name>_2`, `<in>_<name>_3`, …. A schema that\n * mints nothing (a primitive, a `$ref`) keeps the parameter's name at once.\n * When a candidate changes none of the clashing names — they do not embed\n * the property, as a title-mapped union variant does not — no candidate can\n * avoid the clash, so the earliest trial is kept, under the parameter's own\n * name, and the clash is left to the model merge, as for operations;\n * `MAX_PARAMETER_PROPERTY_ATTEMPTS` is a backstop behind that rule. The\n * caller always takes the returned reference, whether or not the property\n * moved: a variant renamed past a decided enum (`PetAdoptedFilterCircle`,\n * see `mintSchema`) is referenced only by the minted type.\n */\nfunction mintParameter(\n  param: ParameterObject,\n  schema: SchemaObject,\n  parent: string,\n  taken: ReadonlySet<string>,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedSchema {\n  let previous: { minted: MintedSchema; clashing: string } | undefined;\n  // The name the models derive from is the one `extractParams` typed the\n  // parameter under — a header's lower-cased (`foldParameterName`) — so the\n  // reference and the models agree, and neither moves with the header's case.\n  const stem = foldParameterName(param.in, param.name);\n  for (let attempt = 0; ; attempt++) {\n    const property = attempt === 0 ? stem : attempt === 1 ? `${param.in}_${stem}` : `${param.in}_${stem}_${attempt}`;\n    const minted = mintSchema(schema, property, parent, componentSchemas, reserved);\n    const clashing = [...minted.names]\n      .filter((name) => taken.has(name))\n      .sort()\n      .join('\\n');\n    if (clashing === '' || attempt >= MAX_PARAMETER_PROPERTY_ATTEMPTS) return minted;\n    // The clash did not move with the property: what clashes are names that\n    // do not embed it (a title-mapped variant), which no candidate can clear\n    // — keep the earliest trial, under the parameter's own name, and leave\n    // the clash to the model merge. Judged on the clashing names alone, since\n    // a name that does embed the property (a variant renamed past a decided\n    // enum, `PetAdoptedXShapeCircle`) changes with every candidate.\n    if (previous !== undefined && previous.clashing === clashing) return previous.minted;\n    previous = { minted, clashing };\n  }\n}\n\n/** Hard cap on the properties `mintParameter` tries; the no-progress rule stops it long before in practice. */\nconst MAX_PARAMETER_PROPERTY_ATTEMPTS = 64;\n\n/**\n * Type `schema` as the synthetic property `property` of `parent` and\n * materialize what it declares inline, collecting every name that minted:\n * the models, and every inline enum (an enum ref carrying `values`; a `$ref`\n * to a component enum carries none and is a reference, not a minting) in the\n * reference and in the models' fields. Component references are deliberately\n * not names: a payload that refers to `AdoptionEvent` names nothing new.\n * A model minted under a name among `reserved.enums` — a title-mapped union\n * variant `Circle` beside a component enum `Circle`, which a property of the\n * same payload may reference — is renamed under the minted root\n * (`PetAdoptedPayloadCircle`; numbered when that is taken too, by anything\n * in `reserved.all` or minted here) with every reference among the models\n * and in the returned type rewritten, as `materializeInlineSchema` renames\n * one under a response body's root; an explicit `$ref` to a component model\n * of the name is never touched, and the enum reference is an `EnumRef`,\n * which no rename reaches. A model and an enum under one name would reach an\n * emitter as one public symbol. A variant named like a decided MODEL is left\n * to the stem hash and the model merge, as before: the names minted here are\n * not reserved from the extractor, so a stem-embedded clash still hashes the\n * stem and a context-free one still reaches the merge.\n */\nfunction mintSchema(\n  schema: SchemaObject,\n  property: string,\n  parent: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedSchema {\n  const models: Model[] = [];\n  extractInlineModelsFromProperties({ properties: { [property]: schema } }, models, parent, componentSchemas);\n  const ref = schemaToTypeRef(schema, property, parent);\n  const root = qualifyInlineModelName(toPascalCase(property), parent);\n  const taken = new Set([...reserved.all, ...models.map((model) => model.name)]);\n  for (const model of models) {\n    if (!reserved.enums.has(model.name)) continue;\n    const from = model.name;\n    let to = `${root}${from}`;\n    for (let n = 2; taken.has(to); n++) to = `${root}${from}${n}`;\n    taken.add(to);\n    model.name = to;\n    for (const other of models) {\n      for (const typeRef of collectModelTypeRefs(other)) repointMintedRefs(typeRef, from, to);\n    }\n    repointMintedRefs(ref, from, to);\n  }\n  const names = new Set<string>();\n  const collectEnums = (typeRef: TypeRef): void => {\n    walkTypeRef(typeRef, {\n      enum: (r) => {\n        if (r.values) names.add(r.name);\n      },\n    });\n  };\n  for (const model of models) {\n    names.add(model.name);\n    for (const field of model.fields) collectEnums(field.type);\n  }\n  collectEnums(ref);\n  return { ref, models, names };\n}\n\n/**\n * Repoint every reference to the minted model `from` within `ref` to `to`,\n * an explicit `$ref` to a component of that name excepted\n * (`isComponentModelRef`); a discriminator mapping naming the model follows.\n */\nfunction repointMintedRefs(ref: TypeRef, from: string, to: string): void {\n  switch (ref.kind) {\n    case 'model':\n      if (ref.name === from && !isComponentModelRef(ref)) (ref as { name: string }).name = to;\n      return;\n    case 'array':\n      repointMintedRefs(ref.items, from, to);\n      return;\n    case 'nullable':\n      repointMintedRefs(ref.inner, from, to);\n      return;\n    case 'map':\n      repointMintedRefs(ref.valueType, from, to);\n      if (ref.keyType) repointMintedRefs(ref.keyType, from, to);\n      return;\n    case 'union':\n      for (const variant of ref.variants) repointMintedRefs(variant, from, to);\n      for (const [value, target] of Object.entries(ref.discriminator?.mapping ?? {})) {\n        if (target === from) ref.discriminator!.mapping[value] = to;\n      }\n      return;\n    default:\n      return;\n  }\n}\n\nfunction buildWebhook(\n  entry: WebhookEntry,\n  minted: MintedShape,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n): Webhook {\n  const { name, method, op, pathItem, body, label } = entry;\n  const {\n    headerParams,\n    queryParams,\n    cookieParams,\n    requestBody,\n    requestBodyEncoding,\n    requestBodyContentType,\n    requestBodyContentTypes,\n    requestBodyContents,\n  } = minted;\n  // Read as an operation's are: the operation's own `summary` and\n  // `description`, or the path item's for each it declares none for.\n  const { summary, description } = resolveOperationDocs(op, pathItem);\n  const tags = extractTags(op.tags);\n  const security = extractSecurityRequirements(op.security, label);\n  // The payload's doc text, read as an operation's body's is: the Request\n  // Body Object's own, else its picked schema's (`requestBodyDescriptionOf`).\n  const requestBodyDescription = requestBodyDescriptionOf(body, selectRequestBodyContent(body));\n\n  return {\n    name,\n    ...(typeof op.operationId === 'string' && op.operationId !== '' ? { operationId: op.operationId } : {}),\n    httpMethod: method,\n    ...(summary !== undefined ? { summary } : {}),\n    ...(description !== undefined ? { description } : {}),\n    // The operation's own link, present only when usable, as on an operation.\n    // A Path Item Object has no `externalDocs` field, so there is no path-item\n    // level to fall back to.\n    ...externalDocsEntry(op.externalDocs),\n    ...(op.deprecated === true ? { deprecated: true } : {}),\n    ...(tags !== undefined ? { tags } : {}),\n    headerParams,\n    queryParams,\n    ...(cookieParams.length > 0 ? { cookieParams } : {}),\n    ...(requestBody ? { requestBody } : {}),\n    ...(requestBodyEncoding ? { requestBodyEncoding } : {}),\n    ...(requestBodyContentType ? { requestBodyContentType } : {}),\n    ...(body?.required === true ? { requestBodyRequired: true } : {}),\n    ...(requestBodyDescription !== undefined ? { requestBodyDescription } : {}),\n    // Every media type the body declares, present only when there is one, as on an operation.\n    ...(requestBodyContentTypes ? { requestBodyContentTypes, requestBodyContents } : {}),\n    responses: extractWebhookResponses(op.responses, components.responses, label, siblingDocs),\n    ...(security !== undefined ? { security } : {}),\n  };\n}\n\n/**\n * The status codes the sender expects back, in document order. Only status\n * code keys (three digits, 100–599, as `classifyResponseKey` decides) are\n * carried: `default` and ranges such as `2XX` name no single code a handler\n * could return, and an `x-` key is a specification extension, so those are\n * skipped silently; a key OpenAPI does not define (`error`, `6XX`, `600`) is\n * warned about and ignored, as on an operation. A response written as a\n * `$ref` into `components/responses` is followed for its description, chains\n * included; a description written beside the `$ref` wins over the\n * component's under `siblingDocs: 'override'` (OpenAPI 3.1) and is ignored\n * under `'ignore'` (3.0), as beside every Reference Object\n * (`followReference`). A ref that leads nowhere, or anywhere else, keeps the\n * status code without a description, with a warning. A blank description is\n * omitted.\n */\nfunction extractWebhookResponses(\n  responses: OperationObject['responses'],\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  label: string,\n  siblingDocs: SiblingDocs,\n): WebhookResponse[] {\n  const result: WebhookResponse[] = [];\n  for (const [code, raw] of Object.entries(responses ?? {})) {\n    const responseKey = classifyResponseKey(code);\n    if (responseKey.kind === 'unrecognized') warnUnrecognizedResponseKey(code, label);\n    if (responseKey.kind !== 'status') continue;\n    const description = presentText(resolveResponseDescription(raw, componentResponses, code, label, siblingDocs));\n    result.push({ statusCode: responseKey.code, ...(description !== undefined ? { description } : {}) });\n  }\n  return result;\n}\n\n/**\n * The description of a response, following a `components/responses` `$ref`\n * chain through `followReference`, the walk every Reference Object takes:\n * the outermost sibling description with content wins under `'override'`\n * and the component's own is read under `'ignore'`. A chain that loops, a\n * `$ref` that is not a string, or a ref nothing answers is warned about and\n * the walk's last object read as written.\n */\nfunction resolveResponseDescription(\n  raw: unknown,\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  code: string,\n  label: string,\n  siblingDocs: SiblingDocs,\n): string | undefined {\n  if (!isRecord(raw)) return undefined;\n  const followed = followReference<{ description?: unknown }>(raw, 'responses', componentResponses, siblingDocs);\n  if (followed.outcome === 'circular' || followed.outcome === 'malformed') {\n    console.warn(\n      `[oagen] Warning: Circular or malformed response $ref for status ${code} in ${label}; keeping the status code only.`,\n    );\n  } else if (followed.outcome === 'unresolved') {\n    console.warn(\n      `[oagen] Warning: Unresolved response $ref \"${followed.ref}\" for status ${code} in ${label}: ` +\n        'no matching entry under components/responses. Keeping the status code only.',\n    );\n  }\n  const { description } = followed.value;\n  return typeof description === 'string' ? description : undefined;\n}\n","import type { Enum, Model, ModelRef, Service, TypeRef, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  collectResponseHeaders,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectOperationTypeRefs,\n  collectWebhookTypeRefs,\n  renameModelRefs,\n  renameTypeRefModels,\n} from '../ir/types.js';\nimport { modelFingerprint } from './operations.js';\nimport { isComponentModelRef } from './schemas.js';\nimport { unionShapeKey } from './union-shape.js';\nimport { shapeWithEnumFlags } from './enum-members.js';\nimport {\n  fieldAdmits,\n  inheritedModelRefsOf,\n  isInheritedModelRef,\n  liftedFieldModelsOf,\n  modelAdmits,\n  modelShares,\n  recordFieldModelRename,\n  shapeFingerprint,\n  typeShapeKey,\n  type FieldInlineModelGroup,\n  type InlineModelBundle,\n  type ShapeReadOptions,\n} from './inline-models.js';\n\n/**\n * What the merge passes need to keep two definitions of one name apart — a\n * deprecated and a live one, an inline one and a component that does not\n * admit it, or an inline model and an enum (see `settleSharedNames`): the\n * site each inline model came from (`bundles`), so the copy that must leave\n * the shared name can be renamed and exactly its own references repointed;\n * every name already in play (`reserved`) — the component models and enums,\n * and every inline model of every pass — so the new name is free; and the\n * enum names among them (`enums`), which no inline model may keep, whatever\n * its shape: when the component fields are settled before the operations\n * are read (`settleFieldInlineModels`), the names `spec.enums` holds — the\n * component enums and the inline enums lifted from the component schemas'\n * own fields, union variants and array items; when the merges run, every\n * enum name in play — those, and every inline enum an operation's or a\n * webhook's reference carries (`reservedNamesByKind`). A name minted here is\n * added to `reserved`, so both passes, and every mint within one, agree, and\n * to `minted`, so a later pass can tell a copy whose fields reference a\n * model an earlier pass renamed — a parent whose child left a shared name —\n * from one that merely shares a name (`settleSharedNames`); a minted name is\n * taken against every name in play, so it names that one model and nothing\n * else. Absent, `minted` is created on first use, so a caller that gives\n * none still gets it within a pass; the parser hands one set to every pass.\n */\nexport interface InlineModelNaming {\n  bundles: InlineModelBundle[];\n  reserved: Set<string>;\n  enums: ReadonlySet<string>;\n  minted?: Set<string>;\n}\n\n/**\n * Bundle the models each component field produced with the references that\n * field owns: its own type, looked up in `models` (the components), and\n * every reference an `allOf` merge has copied from it so far\n * (`inheritedModelRefsOf`), so a renamed child is repointed from the field\n * that produced it and from each copy of that field, and from nowhere else.\n * A field the model no longer has falls back to every field of its\n * component. A rename is recorded for the field (`recordFieldModelRename`),\n * so a reference an `allOf` merge copies from it afterwards — an operation's\n * or a webhook's, read after the fields are settled — is created under the\n * settled name. Read once before the operations (`settleFieldInlineModels`)\n * and again, with the copies made since, before the merges.\n *\n * `models` also holds the models the schema pass lifted from the same\n * inline schemas (`extractSchemas`: a component field's object, array items\n * or union variant, named as the field extractor names them), each\n * remembered by the field it was read from (`liftedFieldModelsOf`). Those\n * lifted from the group's own field are the group's twins, read from the\n * same schema: the group's copy folds onto its twin when the fields are\n * settled, and from then on the twin's own field references — minted for\n * the same nested objects the group holds — are the site's. The twins join\n * the bundle's `models`, so a rename of one of the group's models is\n * repointed in them as in the copy, and a copy whose child was renamed\n * still folds onto its twin. A twin is claimed by origin, never by name:\n * `Foo.barThing` and `FooBar.thing` both spell `FooBarThing`, only one of\n * them is lifted, and the other field's site leaves it alone. Claimed from\n * the moment it is lifted, the twin is in the site at the settle too, so a\n * child renamed there (against a component of its name) is repointed in\n * the twin as in the copy, and the copy still folds onto it rather than\n * take a name of its own and leave the twin referenced by nothing. A direct\n * caller whose schemas were not read by `extractSchemas` has no twins, and\n * its groups are bundled with their own models alone. The twin is among the\n * bundle's `models`, so a reference a header, parameter or fallback body\n * wrote by sharing it joins the field's site like one sharing a field model\n * (`attachSharedRefs`, run over the bundles once the operations are read)\n * and follows the site's renames.\n */\nexport function fieldInlineModelBundles(groups: FieldInlineModelGroup[], models: Model[]): InlineModelBundle[] {\n  const byName = new Map(models.map((m) => [m.name, m]));\n  return groups.map(({ parentName, fieldName, models: fieldModels }) => {\n    const parent = byName.get(parentName);\n    const field = parent?.fields.find((f) => f.name === fieldName);\n    const own = field ? [field.type] : (parent?.fields.map((f) => f.type) ?? []);\n    return {\n      qualifier: parentName,\n      roots: [...own, ...inheritedModelRefsOf(parentName, fieldName)],\n      models: [...fieldModels, ...liftedFieldModelsOf(parentName, fieldName)],\n      renamed: (from, to) => recordFieldModelRename(parentName, fieldName, from, to),\n    };\n  });\n}\n\n/**\n * The same field sites (`fieldInlineModelBundles`, one per group in order)\n * brought up to date for the merges, in place, once the operations and\n * webhooks are read: each site's roots gain the references an `allOf` merge\n * has copied from the field since (`inheritedModelRefsOf`), and its models\n * are the field models that survived the settle (`kept`) and the twins the\n * schema pass lifted — a copy that folded at the settle is dropped from the\n * site, so a site is never taken for the owner of a name it lost\n * (`attachSharedRefs` reads a site's names off its models: `Foo.barThing`\n * and `FooBar.thing` both folded onto the one lifted `FooBarThing`, and\n * `Foo.barThing`'s reference must reach that twin's site). The site objects\n * are kept rather than rebuilt, so what a fold carried onto one at the\n * settle (`InlineModelBundle.carried`) is still there when the field merge\n * renames the model it was carried onto.\n */\nexport function refreshFieldInlineModelBundles(\n  bundles: InlineModelBundle[],\n  groups: FieldInlineModelGroup[],\n  kept: readonly Model[],\n): InlineModelBundle[] {\n  const survivors = new Set(kept);\n  groups.forEach(({ parentName, fieldName }, i) => {\n    const bundle = bundles[i];\n    if (!bundle) return;\n    for (const ref of inheritedModelRefsOf(parentName, fieldName))\n      if (!bundle.roots.includes(ref)) bundle.roots.push(ref);\n    const twins = liftedFieldModelsOf(parentName, fieldName);\n    bundle.models = bundle.models.filter((model) => survivors.has(model) || twins.includes(model));\n  });\n  return bundles;\n}\n\n/**\n * Every type name the document will have minted by the time the IR is\n * finished, so a merge pass that must rename an inline model takes a name\n * nothing else has: the component models and enums, every inline model of\n * either pass (header models, list-envelope companions and union variants\n * included), and every inline enum — named on its `EnumRef` when the field,\n * parameter or header was typed, and only lifted into `spec.enums` after the\n * merges have run — found in any model's fields or named-union variants, or\n * anywhere on an operation or webhook. `reservedNamesByKind` gives the same\n * set beside the enum names among it.\n */\nexport function reservedTypeNames(\n  models: Model[],\n  enums: Enum[],\n  inlineModels: Model[],\n  fieldInlineModels: Model[],\n  services: Service[],\n  webhooks: Webhook[] = [],\n): Set<string> {\n  return reservedNamesByKind(models, enums, inlineModels, fieldInlineModels, services, webhooks).all;\n}\n\n/**\n * `reservedTypeNames` (`all`) beside the enum names among them (`enums`):\n * every enum in `enums` and every inline enum a model's field or variant, an\n * operation's reference or a webhook's carries — every enum name in play,\n * which no inline model the merge passes settle may keep\n * (`InlineModelNaming.enums`). One walk decides both, so the two sets\n * always agree on what an `EnumRef` names.\n */\nexport function reservedNamesByKind(\n  models: Model[],\n  enums: Enum[],\n  inlineModels: Model[],\n  fieldInlineModels: Model[],\n  services: Service[],\n  webhooks: Webhook[] = [],\n): { all: Set<string>; enums: Set<string> } {\n  const all = new Set<string>();\n  const enumNames = new Set<string>();\n  const visit = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        all.add(r.name);\n        enumNames.add(r.name);\n      },\n    });\n  };\n  for (const model of [...models, ...inlineModels, ...fieldInlineModels]) {\n    all.add(model.name);\n    for (const ref of collectModelTypeRefs(model)) visit(ref);\n  }\n  for (const e of enums) {\n    all.add(e.name);\n    enumNames.add(e.name);\n  }\n  for (const service of services) {\n    for (const op of service.operations) for (const ref of collectOperationTypeRefs(op)) visit(ref);\n  }\n  for (const webhook of webhooks) for (const ref of collectWebhookTypeRefs(webhook)) visit(ref);\n  return { all, enums: enumNames };\n}\n\n/**\n * Which references a merge pass may repoint when it renames an inline model,\n * by the reference's identity rather than its name alone: one minted for an\n * inline model, never an explicit `$ref` to a same-named component\n * (`isComponentModelRef`); and a reference an `allOf` merge copied from\n * another component's field (`isInheritedModelRef`) only for that field's\n * own site (`includeInherited`), since it belongs to that site. Handed to\n * `renameTypeRefModels`, so a union's discriminator mapping follows a\n * repointed variant and stays on a `$ref` left in place.\n */\nfunction inlineRefAdmit(includeInherited: boolean): (ref: ModelRef) => boolean {\n  return (ref) => !isComponentModelRef(ref) && (includeInherited || !isInheritedModelRef(ref));\n}\n\n/** The site each inline model of `naming` came from, by identity (`InlineModelBundle.models`). */\nfunction bundlesByModel(naming: InlineModelNaming | undefined): Map<Model, InlineModelBundle> {\n  const bundleOf = new Map<Model, InlineModelBundle>();\n  for (const bundle of naming?.bundles ?? []) {\n    for (const model of bundle.models) bundleOf.set(model, bundle);\n  }\n  return bundleOf;\n}\n\n/**\n * One definition per name among `models`, the pass's own choice: the one\n * with the most fields, the first declared on a tie, with a warning when\n * the definitions differ. Every other copy of the name is folded onto it\n * (`foldOnto`): with `naming`, the copy's site is carried onto the winner,\n * so a later rename of the winner through its own site repoints the copy's\n * references too — a component field's model that lost its name to a\n * homonymous field's larger model (`Foo.barThings` and `FooBar.things` both\n * minting `FooBarThing`) still follows that model off an enum's name. The\n * rule the final field merge applies, applied as soon as the field models\n * are settled, so the model a later pass meets under a name is the one that\n * survives it.\n */\nfunction keepLargestByName(models: Model[], naming?: InlineModelNaming): Model[] {\n  const byName = new Map<string, Model>();\n  for (const model of models) {\n    const existing = byName.get(model.name);\n    if (existing && !haveSameFields(existing, model)) {\n      // Two inline models resolved to one name but describe different shapes\n      // (e.g. two operationIds that PascalCase to the same word). Only one can\n      // survive, so say which, instead of silently handing every other\n      // reference a model with someone else's fields.\n      const kept =\n        model.fields.length === existing.fields.length\n          ? 'keeping the first definition'\n          : 'keeping the one with more fields';\n      console.warn(\n        `[oagen] Warning: Inline model \"${model.name}\" has more than one definition with different fields or field types (${model.fields.length} vs ${existing.fields.length}) — ${kept}`,\n      );\n    }\n    if (!existing || model.fields.length > existing.fields.length) {\n      byName.set(model.name, model);\n    }\n  }\n  const bundleOf = bundlesByModel(naming);\n  const folded = new Map<Model, Model>();\n  for (const model of models) {\n    const winner = byName.get(model.name)!;\n    if (winner !== model) foldOnto(model, winner, bundleOf, folded);\n  }\n  return [...byName.values()];\n}\n\n/**\n * Settle every name an inline model shares with another definition before a\n * merge pass folds same-named models together, so a live operation or field\n * never resolves to a model marked `deprecated`, and no reference resolves to\n * a component of another shape, whatever order the document declares them\n * in.\n *\n * `owners` are the models whose name, shape and flag are authoritative — the\n * component schemas (and, in the field pass, every model the response pass\n * already settled, when the caller does not say which are components) — and\n * `contenders` the inline models competing for their names. For each name,\n * the flag the name carries is its owner's or, with no owner, live as soon\n * as any contender is live (a name every contender deprecates stays\n * deprecated, and the pass leaves it alone).\n *\n * A contender whose flag disagrees with the name's\n *\n * - folds onto the live definition — the one `keepLargestByName` would keep\n *   among the live contenders — when there is no owner and it is identical\n *   to every live contender in everything but the flag\n *   (`differOnlyByDeprecation`): the shared name keeps the live definition,\n *   with a warning, in either order; the deprecated schema's own field or\n *   operation still carries its flag. Live contenders that disagree among\n *   themselves are settled by document order (first declared, or the one with\n *   more fields), as they always were; a deprecated copy never inherits that\n *   tie and is qualified instead, so its name is the same in every order;\n * - folds onto a live owner, with the same warning, when the owner shares\n *   its name with it (`ownerSharesWith`, the flag read apart from the shape\n *   by `flagAdmits`): the copy is dropped and its references resolve to the\n *   owner, the deprecated schema's own field, parameter or envelope field\n *   still carrying the flag (a request body or response has no flag of its\n *   own to carry it). An owner is never renamed and never takes a\n *   contender's flag; a deprecated owner shares its name with no live copy,\n *   whatever their shapes, so a live inline copy never folds onto a\n *   deprecated component;\n * - otherwise takes a name of its own (`renameInlineCopy`).\n *\n * A contender whose flag agrees with an owner's\n *\n * - folds onto the owner when the owner shares its name with it\n *   (`ownerSharesWith`: `modelAdmits` — the same fields and types, the owner\n *   no stricter on requiredness or nullability, everything else identical —\n *   or an identical shape for a copy the SDK sends): the copy is dropped and\n *   its references, which already carry the name, resolve to the owner, and\n *   its site joins the owner's (`foldOnto`), so a later rename of an owner\n *   that has a site — a field model, a lifted twin — repoints them with the\n *   owner's own. An owner is never replaced, whatever the copy's field\n *   count, so every `$ref` to a component keeps the shape the document\n *   declares;\n * - otherwise takes a name of its own (`renameInlineCopy`), with a note. Two\n *   contenders of one name without an owner are left to the pass's own choice\n *   (`keepLargestByName`).\n *\n * A contender named like an enum (`naming.enums`) with no owner of that\n * name takes a name of its own whatever its shape or flag, with a note —\n * identical copies one name per shape, as under an owner (`renameClusters`):\n * an enum admits no model, so the IR never declares a model and an enum\n * under one name. A name both a component model and an enum hold is the\n * document's own clash and is settled as the model's.\n *\n * A renamed copy takes its site's qualifier prefixed (`mintQualifiedName`) —\n * `GetLegacyWidgetWidget` or `GetWidgetWidget` for a response of\n * `getLegacyWidget` or `getWidget` pinned by `object: widget`,\n * `GetPetResponse2` or `CreateNoteRequest2` for a body already named from\n * its operation, `PetOwner2` for a field of `Pet` — minted against every name\n * in play, and the references minted for it are repointed, by identity\n * (`repointInlineModelRefs`): the references its site owns — the operation's\n * response or body, the component field and every `allOf` copy of that\n * field — and those in the fields of the models minted beside it\n * (`InlineModelBundle`); never an explicit `$ref` to a same-named component,\n * in the same response map or anywhere else, and never a reference another\n * site's field lent.\n *\n * Every copy that must leave a name leaves it through `renameClusters`,\n * whichever rule above moves it — the owner's shape, its flag, an enum\n * holding the name, a renamed child (below): identical copies\n * (`modelFingerprint`, the flag included, so a deprecated copy and a live\n * one never cluster) share one renamed model under the first site's\n * qualified name, every site repointed to it, with one note saying how many\n * sites share it; a copy of another shape takes a name of its own. Two\n * deprecated `address` objects beside a live `PetOwnerAddress` of another\n * shape are one `PetOwnerAddress2`, as they would be one `PetOwnerAddress`\n * without the component.\n *\n * Names are decided bottom-up — a name after every name its contenders'\n * fields reference, as the list-envelope pass decides nested companions —\n * so when a parent is compared its children are already named: a parent\n * whose child was just renamed no longer looks identical to its twin, or\n * admitted by its component, and keeps its own model, referencing the\n * renamed child. Under a component, that is the rule above (a copy the\n * owner does not share is qualified). Among the contenders of one flag\n * without an owner, where the shared name otherwise keeps whichever\n * definition the pass's own choice settles on (`keepLargestByName`, by\n * document order), a contender whose fields reference a model this pass or\n * an earlier one renamed (`naming.minted`; a reference the site itself\n * minted, never an explicit `$ref` or one lent by another component's\n * field) is settled the same way as a copy an owner does not share:\n * clustered by shape, each cluster qualified by its first site, with a note\n * — its shape is its site's own now, and folding it by name would leave the\n * renamed child referenced by nothing, or hand every other site the child\n * the pass had just kept off the shared name. The contenders that follow no\n * rename are settled by the pass's own choice, as they always were; when\n * every contender follows one, the first cluster keeps the name as that\n * choice would keep the first definition. A contender under a name a\n * rename minted — the leader of a cluster, which the other sites of the\n * cluster were repointed to — keeps it. The deprecated copies of a live\n * name are compared with the live contenders that keep the name alone.\n *\n * A contender without a site — none the parser produces; a direct caller's —\n * cannot be renamed and is left under the shared name, with a warning: the\n * owner's definition stands and the caller drops the copy.\n *\n * Returns the contenders that still compete for a name, the renamed ones\n * under their new name, and the folded copies keyed to the definition that\n * replaced them — the live twin, or the owner that admitted the copy — so a\n * caller that keeps an owner list can seat the live copy where the folded\n * one was.\n */\nfunction settleSharedNames(\n  owners: Map<string, Model>,\n  contenders: Model[],\n  naming: InlineModelNaming | undefined,\n  yielding?: ReadonlySet<Model>,\n): { kept: Model[]; folded: Map<Model, Model> } {\n  const byName = new Map<string, Model[]>();\n  for (const model of contenders) {\n    const group = byName.get(model.name) ?? [];\n    group.push(model);\n    byName.set(model.name, group);\n  }\n  const bundleOf = bundlesByModel(naming);\n  const flagOf = (deprecated: boolean): string => (deprecated ? 'deprecated' : 'live');\n  // Every name the merge passes have minted so far (`renameInlineCopy`),\n  // shared with the passes before and after this one through `naming`.\n  const minted = naming ? (naming.minted ??= new Set<string>()) : new Set<string>();\n  /**\n   * Whether one of `copy`'s own references — a field's or a variant's,\n   * minted by its site: never an explicit `$ref`, never one lent by another\n   * component's field — names a model a merge pass renamed.\n   */\n  const followsRename = (copy: Model): boolean => {\n    let found = false;\n    for (const ref of collectModelTypeRefs(copy)) {\n      walkTypeRef(ref, {\n        model: (r) => {\n          if (inlineRefAdmit(false)(r) && minted.has(r.name)) found = true;\n        },\n      });\n    }\n    return found;\n  };\n\n  const folded = new Map<Model, Model>();\n  /** `copies` clustered by shape (`modelFingerprint`), in their order — the clusters `renameClusters` forms. */\n  const byShape = (copies: Model[]): Model[][] => {\n    const clusters = new Map<string, Model[]>();\n    for (const copy of copies) {\n      const shape = modelFingerprint(copy);\n      clusters.set(shape, [...(clusters.get(shape) ?? []), copy]);\n    }\n    return [...clusters.values()];\n  };\n\n  for (const name of bottomUp(byName)) {\n    const group = byName.get(name)!;\n    let owner = owners.get(name);\n    // An owner that may yield (`yielding`: a component field's model standing\n    // in for a component in the response merge) does not hold its name\n    // against a live copy when it is deprecated itself: a live copy owns a\n    // shared name, so the owner leaves through its own site, with the note a\n    // deprecated copy gets (`PetNoteOwner2` for `Pet.note.owner` beside\n    // `getA`'s live owner), and the live copies settle the name among\n    // themselves as they would with no owner. A component is never yielded;\n    // its name and flag are the document's.\n    if (owner && yielding?.has(owner) && owner.deprecated && group.some((m) => !m.deprecated)) {\n      const bundle = naming && bundleOf.get(owner);\n      if (bundle) {\n        const renamed = renameInlineCopy(owner, name, bundle, naming);\n        console.warn(`[oagen] Renamed inline model \"${name}\" → \"${renamed}\": it is deprecated while \"${name}\" is live`);\n        owners.delete(name);\n        owner = undefined;\n      }\n    }\n    // A name an enum holds (`naming.enums`) is no model's, whatever the\n    // copy's shape or flag: nothing admits it and nothing folds onto it, so\n    // every copy leaves the name through its site, identical copies sharing\n    // one model under the new name as they do under an owner's\n    // (`renameClusters`). Live and deprecated copies never share a model\n    // (`differOnlyByDeprecation`), so each flag's copies cluster on their\n    // own. A name both a component model and an enum hold is the document's\n    // own clash and is settled as the model's, below.\n    if (!owner && naming?.enums.has(name)) {\n      for (const deprecated of [false, true]) {\n        renameClusters(\n          name,\n          group.filter((copy) => !!copy.deprecated === deprecated),\n          naming,\n          bundleOf,\n          folded,\n          `enum \"${name}\" owns the name`,\n          `[oagen] Warning: Inline model \"${name}\" is named like enum \"${name}\" and has no site to be renamed from — keeping both under the shared name`,\n        );\n      }\n      continue;\n    }\n    let nameDeprecated: boolean;\n    /** The live contenders a deprecated copy may fold onto; empty under an owner, which every copy is measured against instead (`ownerSharesWith`). */\n    let live: Model[] = [];\n    if (owner) {\n      nameDeprecated = !!owner.deprecated;\n    } else {\n      nameDeprecated = group.every((m) => m.deprecated);\n      const holders = group.filter((m) => !!m.deprecated === nameDeprecated);\n      // A holder of the name that follows a rename — a parent whose child\n      // left a shared name — is its site's own shape now, and leaves the\n      // name by its site rather than by the pass's choice between twins\n      // (`keepLargestByName`), which would drop it and orphan the child, or\n      // keep it and hand every other site the child the pass kept off the\n      // name. A holder under a name a rename minted is the leader the other\n      // sites of its cluster were repointed to, and keeps it. The twins that\n      // follow no rename are settled as always; when every holder follows\n      // one, the first cluster keeps the name as the pass's choice would\n      // keep the first definition. The copies of the other flag below are\n      // measured against the holders that keep the name alone.\n      const own = holders.filter((m) => !minted.has(m.name) && followsRename(m));\n      const rest = holders.filter((m) => !own.includes(m));\n      const leaving = byShape(own);\n      const first = rest.length === 0 ? (leaving.shift() ?? []) : [];\n      renameClusters(\n        name,\n        leaving.flat(),\n        naming,\n        bundleOf,\n        folded,\n        `it references a renamed model and \"${name}\" keeps another definition`,\n        `[oagen] Warning: Inline model \"${name}\" references a renamed model, is named like another definition and has no site to be renamed from — keeping the usual definition under the shared name`,\n      );\n      live = holders.filter((m) => rest.includes(m) || first.includes(m));\n      if (live.length === 0 || holders.length === group.length) continue;\n    }\n\n    // Under an owner, every copy is measured against it first: one the\n    // owner shares its name with (`ownerSharesWith`, the flag read by\n    // `flagAdmits`) is folded onto it — a deprecated copy onto a live owner\n    // with the warning two inline copies get, since the shared name keeps\n    // the live definition; a deprecated owner shares with no live copy. The\n    // copies that agree with the name's flag and that the owner does not\n    // share leave the owner's name, one model per shape (`renameClusters`).\n    // A copy whose flag disagrees and that the owner does not share leaves\n    // the name the same way, below.\n    const clashing: Model[] = [];\n    for (const copy of group) {\n      if (!owner) continue;\n      const bundle = naming && bundleOf.get(copy);\n      if (ownerSharesWith(owner, copy, bundle)) {\n        if (!!copy.deprecated !== nameDeprecated) {\n          console.warn(\n            `[oagen] Warning: Inline model \"${name}\" is declared both deprecated and live with the same shape — keeping the live definition under the shared name`,\n          );\n        }\n        foldOnto(copy, owner, bundleOf, folded);\n        continue;\n      }\n      if (!!copy.deprecated !== nameDeprecated) continue;\n      clashing.push(copy);\n    }\n    renameClusters(\n      name,\n      clashing,\n      naming,\n      bundleOf,\n      folded,\n      `its shape differs from component schema \"${name}\"`,\n      `[oagen] Warning: Inline model \"${name}\" has a different shape than component schema \"${name}\" and has no site to be renamed from — using the component schema`,\n    );\n\n    // The copies whose flag disagrees with the name's and that nothing takes\n    // in — no owner that shares the name, no live twin — leave it the same\n    // way, clustered by shape in document order: two identical deprecated\n    // `address` objects beside a live `PetOwnerAddress` of another shape, or\n    // beside live inline copies they do not twin, are one `PetOwnerAddress2`\n    // rather than a `PetOwnerAddress2` and a `PetOwnerAddress3`, and two\n    // identical live copies beside a deprecated component share one name the\n    // same way. The note names the copies' flag and the name's; every copy\n    // here carries the one flag the name does not.\n    const disagreeing: Model[] = [];\n    for (const copy of group) {\n      if (!!copy.deprecated === nameDeprecated || folded.has(copy)) continue;\n      // Without an owner, a deprecated copy folds only when every live copy\n      // of the name is its twin but for the flag: then whichever live\n      // definition the shared name carries, the copy is interchangeable with\n      // it. Live copies that disagree among themselves (requiredness, say)\n      // are settled by document order, as always; a deprecated copy must not\n      // inherit that order, so it is qualified whenever they disagree.\n      if (live.length > 0 && live.every((l) => differOnlyByDeprecation(l, copy))) {\n        console.warn(\n          `[oagen] Warning: Inline model \"${name}\" is declared both deprecated and live with the same shape — keeping the live definition under the shared name`,\n        );\n        foldOnto(copy, preferredDefinition(live), bundleOf, folded);\n        continue;\n      }\n      disagreeing.push(copy);\n    }\n    renameClusters(\n      name,\n      disagreeing,\n      naming,\n      bundleOf,\n      folded,\n      `it is ${flagOf(!nameDeprecated)} while \"${name}\" is ${flagOf(nameDeprecated)}`,\n      `[oagen] Warning: Inline model \"${name}\" is ${flagOf(!nameDeprecated)} in one definition and ${flagOf(nameDeprecated)} in another, with different shapes, and has no site to be renamed from — keeping the usual definition under the shared name`,\n    );\n  }\n\n  return { kept: contenders.filter((m) => !folded.has(m)), folded };\n}\n\n/**\n * Whether `owner`, a component, shares its name with `copy` (`modelShares`):\n * when it admits the shape (`modelAdmits`) — or, for a copy the SDK sends\n * (`bundle.sent`: a request body, a parameter), only when the shapes are\n * identical, since a caller typed against a looser component could leave\n * out what the operation requires — the flag read apart from the shape\n * either way (`flagAdmits`: a live owner shares with a deprecated copy, a\n * deprecated owner only with a deprecated one). The same question\n * `ownerShares` answers for the shape registry.\n */\nfunction ownerSharesWith(owner: Model, copy: Model, bundle: InlineModelBundle | undefined): boolean {\n  return modelShares(owner, copy, !!bundle?.sent);\n}\n\n/**\n * Move `copy` off `name` to a free name qualified by its site\n * (`mintQualifiedName`), reserve it, record it as minted\n * (`InlineModelNaming.minted`, so a parent referencing it is told from a\n * mere namesake), and repoint exactly the references its site minted\n * (`repointSite`). Returns the new name.\n */\nfunction renameInlineCopy(copy: Model, name: string, bundle: InlineModelBundle, naming: InlineModelNaming): string {\n  const renamed = mintQualifiedName(name, bundle.qualifier, naming.reserved);\n  naming.reserved.add(renamed);\n  naming.minted?.add(renamed);\n  copy.name = renamed;\n  repointSite(bundle, name, renamed, copy);\n  return renamed;\n}\n\n/**\n * Repoint exactly the references a site minted for `name` to `renamed`\n * (`inlineRefAdmit`): the site's own roots, copies of its field included;\n * then the references in the models minted beside it, which never include\n * what another site's field lent them — every reference kind alike, a\n * union's discriminator mapping following its variant\n * (`renameTypeRefModels`, `renameModelRefs`); then, for `model` — the model\n * of the site leaving `name` — the sites of the copies that folded onto it\n * (`InlineModelBundle.carried`, read by the model's identity), whose\n * references under `name` are references to it. A site that copies\n * references later is told (`InlineModelBundle.renamed`).\n */\nfunction repointSite(bundle: InlineModelBundle, name: string, renamed: string, model: Model): void {\n  const renames = new Map([[name, renamed]]);\n  for (const root of bundle.roots) renameTypeRefModels(root, renames, inlineRefAdmit(true));\n  for (const m of bundle.models) renameModelRefs(m, renames, inlineRefAdmit(false));\n  for (const entry of bundle.carried ?? []) {\n    if (entry.owner !== model) continue;\n    for (const root of entry.roots) renameTypeRefModels(root, renames, inlineRefAdmit(true));\n    for (const m of entry.models) renameModelRefs(m, renames, inlineRefAdmit(false));\n  }\n  bundle.renamed?.(name, renamed);\n}\n\n/**\n * Fold `copy` onto `winner` — the definition that replaces it under the\n * shared name: a component or a model the document declares, the live twin\n * of a deprecated copy, or the leader of its cluster — and carry its site\n * into the winner's (`InlineModelBundle.carried`), keyed to the winner. The\n * copy's references name the winner from now on, so when the winner is\n * renamed through its own site, the references in the copy's roots and in\n * the models minted beside it that carry the winner's name are repointed\n * with the winner's own (`repointSite`): a field model folded onto while an\n * operation's enum of its name is not yet known still carries the\n * operation's response with it when the field merge moves it off the\n * enum's name. The carried site is read by the winner's identity, never by\n * name: a rename of another model of the winner's site leaves it alone,\n * since a model of the copy's site under that name is the copy's site's\n * own, decided on its own (a parent decided after its children, say, which\n * may keep the name the winner's site's model leaves). A site carried onto\n * the copy earlier is carried on to the winner. A winner without a site — a\n * component — is never renamed, so nothing is carried.\n */\nfunction foldOnto(\n  copy: Model,\n  winner: Model,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n): void {\n  folded.set(copy, winner);\n  const site = bundleOf.get(copy);\n  const into = bundleOf.get(winner);\n  if (!site || !into || site === into) return;\n  const carried = (into.carried ??= []);\n  carried.push({ owner: winner, roots: site.roots, models: site.models.filter((m) => m !== copy) });\n  for (const entry of site.carried ?? []) {\n    if (entry.owner === copy) carried.push({ owner: winner, roots: entry.roots, models: entry.models });\n  }\n}\n\n/**\n * Move `copies` — contenders of `name` that may not keep it, whether a\n * component of another shape or an enum holds it — off the name, one model\n * per shape: the copies are clustered by shape in document order\n * (`modelFingerprint`), the first of a cluster with a site is renamed\n * through it (`renameInlineCopy`) and every later one is repointed to that\n * name (`repointSite`) and folded onto it, so identical copies that must\n * leave a name share one model under the new one, as they would share the\n * bare name with no claimant (`keepLargestByName`). Each cluster's rename is\n * noted as `[oagen] Renamed inline model \"<name>\" → \"<renamed>\": <reason>`,\n * with the number of sites when more than one shares it. A copy without a\n * site cannot be renamed and is left under `name`, `noSite` said for each.\n * The copies must agree on `deprecated`: a cluster never joins a live copy\n * to a deprecated one (`differOnlyByDeprecation`).\n */\nfunction renameClusters(\n  name: string,\n  copies: readonly Model[],\n  naming: InlineModelNaming | undefined,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n  reason: string,\n  noSite: string,\n): void {\n  const clusters = new Map<string, Model[]>();\n  for (const copy of copies) {\n    const shape = modelFingerprint(copy);\n    clusters.set(shape, [...(clusters.get(shape) ?? []), copy]);\n  }\n  for (const cluster of clusters.values()) {\n    let renamed: string | undefined;\n    let leader: Model | undefined;\n    for (const copy of cluster) {\n      const bundle = naming && bundleOf.get(copy);\n      if (!naming || !bundle) {\n        console.warn(noSite);\n        continue;\n      }\n      if (renamed === undefined || leader === undefined) {\n        renamed = renameInlineCopy(copy, name, bundle, naming);\n        leader = copy;\n        continue;\n      }\n      repointSite(bundle, name, renamed, copy);\n      foldOnto(copy, leader, bundleOf, folded);\n    }\n    if (renamed !== undefined) {\n      const sites = cluster.filter((copy) => naming && bundleOf.has(copy)).length;\n      console.warn(\n        `[oagen] Renamed inline model \"${name}\" → \"${renamed}\": ${reason}${sites > 1 ? ` (shared by ${sites} sites)` : ''}`,\n      );\n    }\n  }\n}\n\n/**\n * The names in `groups`, each after every name the models under it reference\n * (through their fields and named-union variants, at any depth of array,\n * map, union or nullable wrapper) — a post-order walk, so a cycle is cut\n * where it closes and every name appears once. Insertion order breaks ties, so the result is as stable\n * as the document.\n */\nfunction bottomUp(groups: ReadonlyMap<string, Model[]>): string[] {\n  const order: string[] = [];\n  const visited = new Set<string>();\n  const visit = (name: string): void => {\n    if (visited.has(name)) return;\n    visited.add(name);\n    for (const model of groups.get(name) ?? []) {\n      for (const ref of collectModelTypeRefs(model)) {\n        walkTypeRef(ref, {\n          model: (r) => {\n            // An explicit `$ref` names a component, never a contender.\n            if (!isComponentModelRef(r) && groups.has(r.name)) visit(r.name);\n          },\n        });\n      }\n    }\n    order.push(name);\n  };\n  for (const name of groups.keys()) visit(name);\n  return order;\n}\n\n/** The definition `keepLargestByName` keeps of a name: the one with the most fields, the first declared on a tie. */\nfunction preferredDefinition(models: Model[]): Model {\n  let best = models[0]!;\n  for (const model of models) if (model.fields.length > best.fields.length) best = model;\n  return best;\n}\n\n/**\n * A free name for a copy that must leave `name`: `qualifier` prefixed, as a\n * list-envelope companion or header model is qualified\n * (`GetLegacyWidgetWidget`), or — when the name already starts with the\n * qualifier, as a request body named from its operation does — the name\n * itself; then, while that is taken, a numeric suffix (`CreateNoteRequest2`,\n * `…3`), the fallback a header model uses. `reserved` holds every name in\n * play, so the search stops at the first free suffix and the result collides\n * with nothing any pass has minted or will mint.\n */\nfunction mintQualifiedName(name: string, qualifier: string, reserved: ReadonlySet<string>): string {\n  const base = name.startsWith(qualifier) ? name : `${qualifier}${name}`;\n  if (base !== name && !reserved.has(base)) return base;\n  for (let n = 2; ; n++) {\n    const candidate = `${base}${n}`;\n    if (!reserved.has(candidate)) return candidate;\n  }\n}\n\n/**\n * Whether `a` and `b` are the same model but for `deprecated` — one flagged,\n * the other not, and otherwise identical in everything the header registry's\n * `modelFingerprint` reads: every field's name, type, requiredness, limits,\n * default and access flags, and the model's own limits, type parameters and\n * discriminator (names and documentation aside). Only such a pair is\n * interchangeable under one name; a difference in requiredness alone would\n * make a deprecated response promise a field the wire may omit.\n */\nfunction differOnlyByDeprecation(a: Model, b: Model): boolean {\n  if (!!a.deprecated === !!b.deprecated) return false;\n  return shapeFingerprint(a) === shapeFingerprint(b);\n}\n\n/**\n * Same field names with the same types, in any order, and the same\n * named-union variants. Types are compared by their JSON serialization: the\n * parser builds a given shape's TypeRef with the same key order every time,\n * so equal shapes serialize identically. An inline enum serializes with its\n * per-value deprecation (`shapeWithEnumFlags`), so a member deprecated on\n * one side only is a different type.\n */\nfunction haveSameFields(a: Model, b: Model): boolean {\n  const signatures = (m: Model) =>\n    new Set([\n      ...m.fields.map((f) => `${f.name}:${JSON.stringify(shapeWithEnumFlags(f.type))}`),\n      ...(m.variants ?? []).map((v, i) => `variant${i}:${JSON.stringify(shapeWithEnumFlags(v))}`),\n    ]);\n  const aSignatures = signatures(a);\n  const bSignatures = signatures(b);\n  return aSignatures.size === bSignatures.size && [...aSignatures].every((s) => bSignatures.has(s));\n}\n\n/** Every type reference in play: each model's fields and variants, each operation's, each webhook's. */\nfunction typeRefsInPlay(\n  models: readonly Model[],\n  services: readonly Service[],\n  webhooks: readonly Webhook[],\n): TypeRef[] {\n  const refs: TypeRef[] = [];\n  for (const model of models) refs.push(...collectModelTypeRefs(model));\n  for (const service of services) for (const op of service.operations) refs.push(...collectOperationTypeRefs(op));\n  for (const webhook of webhooks) refs.push(...collectWebhookTypeRefs(webhook));\n  return refs;\n}\n\n/**\n * Repoint every model reference in `models`, `services` and `webhooks`\n * through `renames` in one pass — fields, named-union variants and\n * discriminator mappings alike — each reference read once, so a name one\n * entry vacates and another takes is never chained through; and, when\n * `inlineEnumName` is given, rename every inline enum reference — one\n * carrying its `values`, named by the extractor after the model and field\n * it sits in — through it the same way, returning each name so renamed with\n * the name it was given. A component enum reference carries no values and\n * is left as written.\n */\nfunction rewriteModelRefs(\n  models: Model[],\n  services: Service[],\n  renames: ReadonlyMap<string, string>,\n  webhooks: Webhook[] = [],\n  inlineEnumName?: (name: string) => string,\n): Map<string, string> {\n  for (const model of models) renameModelRefs(model, renames);\n  for (const service of services) {\n    for (const op of service.operations) {\n      renameTypeRefModels(op.response, renames);\n      if (op.requestBody) renameTypeRefModels(op.requestBody, renames);\n      // The iterator's item type is its own reference when an explicit\n      // `dataPath` typed it from the document (`resolveDataPathFromSchema`),\n      // not the one `response` holds, so it is rewritten on its own.\n      if (op.pagination) renameTypeRefModels(op.pagination.itemType, renames);\n      for (const field of op.pagination?.envelopeFields ?? []) renameTypeRefModels(field.type, renames);\n      for (const error of op.errors) if (error.type) renameTypeRefModels(error.type, renames);\n      for (const header of collectResponseHeaders(op)) renameTypeRefModels(header.type, renames);\n      for (const { type } of collectResponseBodyTypes(op)) renameTypeRefModels(type, renames);\n      for (const { type } of collectRequestBodyTypes(op)) renameTypeRefModels(type, renames);\n    }\n  }\n  for (const webhook of webhooks) {\n    for (const ref of collectWebhookTypeRefs(webhook)) renameTypeRefModels(ref, renames);\n  }\n  const enumRenames = new Map<string, string>();\n  if (!inlineEnumName) return enumRenames;\n  for (const ref of typeRefsInPlay(models, services, webhooks)) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (!r.values) return;\n        const name = inlineEnumName(r.name);\n        if (name === r.name) return;\n        enumRenames.set(r.name, name);\n        r.name = name;\n      },\n    });\n  }\n  return enumRenames;\n}\n\n/**\n * Fold the operations' and webhooks' inline models into the component\n * models. A component's name, shape and flag are authoritative, and among\n * the inline models a live copy owns a shared name, so `settleSharedNames`\n * runs first: an inline model named like a component keeps the name only\n * when the component admits it (and is then dropped, its references\n * resolving to the component) and takes a qualified name otherwise, so a\n * component is never replaced; the fold below (`keepLargestByName`) only\n * ever joins inline models that agree on `deprecated`. An inline model named\n * like one of the document's enums (`naming.enums`) — a request body or\n * primary response named from its operation, a model nested under one, a\n * list-envelope companion — takes a qualified name the same way, whatever\n * its shape. A copy the caller gave no site to rename from (`naming`) is\n * dropped in favour of the component, with the settle pass's warning; one\n * named like an enum is kept beside it, with a warning, since nothing\n * stands in for it.\n *\n * `declared` are the other models the document declares — the components'\n * own field models, settled first (`settleFieldInlineModels`) and merged\n * later (`mergeFieldInlineModels`) — which own their names here exactly as\n * the components do, as they do in the shape registry: an inline model\n * named like one folds onto it when it admits the shape and takes a\n * qualified name otherwise, decided bottom-up before its parent is compared\n * with anything. Read by name alone, a nested object of a response named\n * like a component field's model would pass for it under a parent the\n * lifted model admits, and be left behind, renamed, once the field merge\n * told the two apart. They are not returned: the caller merges them itself.\n */\nexport function mergeInlineResponseModels(\n  schemaModels: Model[],\n  inlineModels: Model[],\n  naming?: InlineModelNaming,\n  declared: Model[] = [],\n): Model[] {\n  return [\n    ...schemaModels,\n    ...settleAgainstComponents([...schemaModels, ...declared], inlineModels, naming, new Set(declared)),\n  ];\n}\n\n/**\n * Settle the components' own inline field models against the components —\n * the first merge step, run as soon as both are extracted and before any\n * operation or webhook is read (see `parseSpec`): a field object, array\n * item or union variant named like a component shares the name when the\n * component admits it — a deprecated one beside a live component included,\n * the field keeping the flag — and is dropped, the field resolving to the\n * component; one the component does not admit, a live one beside a\n * deprecated component included, takes its qualified name now\n * (`PetOwner2`), its field and every `allOf` copy of it repointed\n * (`settleSharedNames`). Settling the fields first means every\n * later comparison with a component — the shape registry's, the response\n * merge's — reads the component's children by their final names, so a body\n * that `$ref`s a component `GetPetResponseOwner` is never admitted by a\n * component whose `owner` was an inline object of another shape that only\n * later becomes `GetPetResponseOwner2`. A field model named like one of the\n * document's enums (`naming.enums`) — a `Pet.owner` object beside a\n * component enum `PetOwner` — takes its qualified name here too (`PetOwner2`),\n * whatever its shape, so the IR never declares a model and an enum under one\n * name. Returns the field models still competing for a name, the renamed\n * ones under their new names; the response merge that follows settles the\n * operations' and webhooks' models against them as against the components\n * (`mergeInlineResponseModels`, `declared`), and the field merge folds them\n * in (`mergeFieldInlineModels`). A copy dropped here for the object the\n * schema pass itself lifted from the same field needs no record: that\n * object is in the field's site from the moment it is lifted\n * (`fieldInlineModelBundles`, `liftedFieldModelsOf`).\n */\nexport function settleFieldInlineModels(\n  components: Model[],\n  fieldInlineModels: Model[],\n  naming?: InlineModelNaming,\n): Model[] {\n  return settleAgainstComponents(components, fieldInlineModels, naming);\n}\n\n/**\n * `contenders` settled against `components` (`settleSharedNames`), minus\n * those that folded onto one and those still named like one — a kept copy\n * still carrying a component's name had no site to be renamed from, and the\n * component's definition stands — then one definition per name among what\n * is left (`keepLargestByName`, the pass's own choice, the folded copies'\n * sites carried), so what the caller returns, and what a later pass meets\n * under a name, is the definition that survives. `yielding` names the\n * components that are field models standing in for components, which yield\n * a name to a live copy when deprecated (`settleSharedNames`).\n */\nfunction settleAgainstComponents(\n  components: Model[],\n  contenders: Model[],\n  naming?: InlineModelNaming,\n  yielding?: ReadonlySet<Model>,\n): Model[] {\n  const owners = new Map(components.map((m) => [m.name, m]));\n  const { kept } = settleSharedNames(owners, contenders, naming, yielding);\n  return keepLargestByName(\n    kept.filter((model) => !owners.has(model.name)),\n    naming,\n  );\n}\n\n/**\n * Fold the field extractor's inline models into the models gathered so far.\n * `componentNames` tells a clash with a real component schema apart from one\n * between two inline models: the components are the owners the field models\n * are settled against, and every other existing model — the response pass's\n * inline survivors — competes with the field models for its name like any\n * inline copy.\n *\n * `settleSharedNames` runs first with the components (every existing model,\n * when the caller does not say which are components) as owners: a field\n * model named like a component keeps the name only when the component\n * admits it (and is then dropped, the field resolving to the component) and\n * takes a qualified name otherwise, so a component is never replaced; and a\n * deprecated and a live definition of one name are told apart. The parser\n * has already settled its field models against the components\n * (`settleFieldInlineModels`) and the response pass's models against the\n * field models (`mergeInlineResponseModels`, `declared`), so for it no\n * survivor shares a field model's name any more and this step only folds\n * the field models in; a direct caller's field models are settled here,\n * and a field model of theirs named like an inline survivor of another\n * shape is dropped in favour of the survivor, with a warning naming both\n * shapes, as the earlier definition of an inline name is kept everywhere.\n * The fold below only joins models that agree on the flag. A field model\n * named like one of the document's enums\n * (`naming.enums`) — a `Pet.owner` object beside a component enum\n * `PetOwner` — takes a qualified name (`PetOwner2`) whatever its shape, as\n * the response pass's models do; the parser's field models meet that rule\n * when they are settled (`settleFieldInlineModels`), a direct caller's here.\n * A copy without a site to rename from (`naming`) is dropped in favour of\n * the component, with the settle pass's warning; one named like an enum is\n * kept beside it, with a warning.\n */\nexport function mergeFieldInlineModels(\n  existingModels: Model[],\n  fieldInlineModels: Model[],\n  componentNames?: Set<string>,\n  naming?: InlineModelNaming,\n): Model[] {\n  const isComponent = (m: Model): boolean => !componentNames || componentNames.has(m.name);\n  const owners = new Map(existingModels.filter(isComponent).map((m) => [m.name, m]));\n  const { kept, folded } = settleSharedNames(\n    owners,\n    [...existingModels.filter((m) => !isComponent(m)), ...fieldInlineModels],\n    naming,\n  );\n  const keptSet = new Set(kept);\n  // An existing inline model folded onto a live field copy of its shape\n  // gives the copy its place; a field copy folded onto anything is simply\n  // dropped.\n  const promoted = new Set<Model>();\n  const retainedModels: Model[] = [];\n  for (const model of existingModels) {\n    if (isComponent(model) || keptSet.has(model)) {\n      retainedModels.push(model);\n      continue;\n    }\n    const winner = folded.get(model);\n    if (winner) {\n      retainedModels.push(winner);\n      promoted.add(winner);\n    }\n  }\n\n  const modelsByName = new Map(retainedModels.map((m) => [m.name, m]));\n  const fieldList = (m: Model): string => m.fields.map((f) => f.name).join(', ') || '(no fields)';\n\n  const deduplicatedFieldModels = fieldInlineModels.filter((model) => {\n    if (!keptSet.has(model) || promoted.has(model)) return false;\n    const existing = modelsByName.get(model.name);\n    if (!existing) return true;\n    // Still named like a component: it could not be renamed (no site), and\n    // the component's definition stands.\n    if (isComponent(existing)) return false;\n\n    const existingFieldNames = new Set(existing.fields.map((f) => f.name));\n    const inlineFieldNames = new Set(model.fields.map((f) => f.name));\n    const hasDifference =\n      model.fields.some((f) => !existingFieldNames.has(f.name)) ||\n      existing.fields.some((f) => !inlineFieldNames.has(f.name));\n    if (hasDifference) {\n      console.warn(\n        `[oagen] Warning: Two inline models are named \"${model.name}\" (fields: ${fieldList(existing)} | ${fieldList(model)}) — keeping the first, the second is dropped`,\n      );\n    }\n    return false;\n  });\n\n  return [...retainedModels, ...keepLargestByName(deduplicatedFieldModels, naming)];\n}\n\nfunction hasModelConstDiscriminant(model: Model): boolean {\n  return model.fields.some(\n    (f) => (f.name === 'object' || f.name === 'type') && f.type.kind === 'literal' && typeof f.type.value === 'string',\n  );\n}\n\nfunction isModelReferencedByOthers(name: string, models: Model[], excludeNames: Set<string>): boolean {\n  for (const model of models) {\n    if (excludeNames.has(model.name)) continue;\n    for (const ref of collectModelTypeRefs(model)) {\n      let found = false;\n      walkTypeRef(ref, {\n        model: (r) => {\n          if (r.name === name) found = true;\n        },\n      });\n      if (found) return true;\n    }\n  }\n  return false;\n}\n\n/**\n * The shape `base` has once `json` folds onto it, as a model of its own:\n * `json`'s fields and its named-union metadata — `variants`,\n * `compositionKind` and `discriminator`, each present or absent exactly as\n * on `json`, so a fold never turns a named union back into a plain object —\n * the two models' own limits (minProperties, dependentRequired, ...) merged\n * with `json`'s winning where both speak, `base`'s own link or `json`'s\n * where it has none, and `base`'s name, description and `deprecated`:\n * deprecation names the type the SDK exposes, and that is `base`, so a\n * deprecated `<Name>Json` folded into a live `<Name>` leaves `<Name>` live.\n * A base that dispatches by rules `json` does not preserve is never folded\n * (`collapseJsonSuffixModels` refuses it), so this only ever adds union\n * metadata to a plain base or replaces a union's with identical rules. The\n * plan reads it to decide what the folded base admits before anything is\n * written; `applyFold` writes it. Every site that copies one model's shape\n * onto another goes through these two.\n */\nfunction foldedShape(base: Model, json: Model): Model {\n  const shape: Model = { ...base, fields: json.fields };\n  delete shape.variants;\n  delete shape.compositionKind;\n  delete shape.discriminator;\n  if (json.variants) shape.variants = json.variants;\n  if (json.compositionKind) shape.compositionKind = json.compositionKind;\n  if (json.discriminator) shape.discriminator = json.discriminator;\n  if (json.constraints || base.constraints) shape.constraints = { ...base.constraints, ...json.constraints };\n  if (!base.externalDocs && json.externalDocs) shape.externalDocs = json.externalDocs;\n  return shape;\n}\n\n/** Write `foldedShape(base, json)` onto `base`, in place. */\nfunction applyFold(base: Model, json: Model): void {\n  const shape = foldedShape(base, json);\n  delete base.variants;\n  delete base.compositionKind;\n  delete base.discriminator;\n  Object.assign(base, shape);\n}\n\n/** A `<Name>Json` model and the `<Name>` model it may fold onto. */\ninterface FoldCandidate {\n  readonly jsonModel: Model;\n  readonly baseModel: Model;\n}\n\n/**\n * How every name reads once the `accepted` folds are applied, as a function\n * of the names the models hold now: a name that begins with an accepted\n * `…Json` model's name is read with that prefix replaced by its base's —\n * the longest such prefix first, then again, until no accepted `…Json` name\n * is a prefix — so `PetJson` reads as `Pet`, `PetJsonWithA` as `PetWithA`,\n * `PetJsonJsonThing` as `PetThing` by way of `PetJsonThing`, and\n * `NoteJsonPetJsonToy` as `NotePetToy` under the folds of `NoteJsonPetJson`\n * and `NoteJson`, whichever the document declares first. Every step\n * shortens the name, so the reading ends. A name no accepted fold touches\n * reads as it is: the fold renames no literal and no component enum.\n */\nfunction foldReading(accepted: readonly FoldCandidate[]): (name: string) => string {\n  const swaps = accepted\n    .map((candidate) => [candidate.jsonModel.name, candidate.baseModel.name] as const)\n    .sort(([a], [b]) => b.length - a.length);\n  const read = new Map<string, string>();\n  const reading = (name: string): string => {\n    const known = read.get(name);\n    if (known !== undefined) return known;\n    const swap = swaps.find(([json]) => name.startsWith(json));\n    const result = swap ? reading(swap[1] + name.slice(swap[0].length)) : name;\n    read.set(name, result);\n    return result;\n  };\n  return reading;\n}\n\n/** The accepted fold whose `…Json` name is the longest prefix of `name` — the one `foldReading` applies to it first — or none when no fold renames it. */\nfunction innermostFold(accepted: readonly FoldCandidate[], name: string): FoldCandidate | undefined {\n  let innermost: FoldCandidate | undefined;\n  for (const candidate of accepted) {\n    if (!name.startsWith(candidate.jsonModel.name)) continue;\n    if (!innermost || candidate.jsonModel.name.length > innermost.jsonModel.name.length) innermost = candidate;\n  }\n  return innermost;\n}\n\n/** The names of the models `model` dispatches to — every model reference among its variants — read under `readName`. */\nfunction variantModelNames(model: Model, readName: (name: string) => string): Set<string> {\n  const names = new Set<string>();\n  for (const variant of model.variants ?? []) walkTypeRef(variant, { model: (r) => names.add(readName(r.name)) });\n  return names;\n}\n\n/**\n * Fold every `<Name>Json` model that is a superset of a `<Name>` model onto\n * it: `<Name>` takes the `…Json` model's shape, every reference to the\n * `…Json` model resolves to `<Name>`, and every `<Name>Json…` child — a\n * model the extractor named under it, or any model spelled that way, inline\n * enums included — is renamed `<Name>…`, or collapsed onto the model that\n * ends under that name when there is one.\n *\n * Pass 1 keeps, as a candidate, each `…Json` model whose base admits the\n * fold on its own terms (the guards below, read against the models as the\n * document left them). Pass 2 decides the candidates together, so the\n * result depends on the document's names and shapes and never on the order\n * it declares them in: every name is read as it ends once the accepted\n * folds are applied (`foldReading`, every model and inline enum reference\n * through `ShapeReadOptions.readName`), a base as the shape it takes\n * (`foldedShape`), and\n *\n * - a candidate whose base dispatches by union rules the `…Json` model does\n *   not preserve, or declares a field the `…Json` model's does not admit\n *   (`fieldAdmits`), is refused;\n * - the models that end under one name are one group: with a model the\n *   folds leave under its own name among them, that model is the holder and\n *   must admit every other (`modelAdmits`), which collapses onto it;\n *   without one, every member must be equivalent (each admits each) and the\n *   first declared keeps the name while the others collapse onto it. A\n *   member not admitted refuses the fold that renames it — the innermost,\n *   when several do — with the union-rules warning when that fold's base\n *   dispatches to the name, else a shape warning. Two folds whose children\n *   would end under one name with different shapes refuse each other.\n *\n * A refusal changes how the remaining names read, so the decision is\n * repeated over the folds still accepted until none is refused; a fold is\n * only ever refused, never re-admitted, so this ends. Only then is anything\n * written: each base takes its shape (`applyFold`), every reference is\n * repointed through the reading at once (`rewriteModelRefs`), the folded\n * `…Json` models and the collapsed members are dropped, and the names are\n * set. Nothing is collapsed by name alone, and nothing is half-applied.\n *\n * An inline enum a fold renames was lifted into `enums` under its old name\n * by the component pass (a `…Json` component's field enum): once no\n * reference carries that name, the entry is dropped and the collectors\n * that run after the fold lift the renamed reference afresh — onto the\n * base's own enum when one has its members (`PetJsonStatus` folds into\n * `PetStatus`), under the new name otherwise (`PetJsonMode` becomes\n * `PetMode`), stepping around a different enum of that name as they do\n * for any inline enum. An enum in `componentNames` is declared by the\n * document and stays whether referenced or not.\n */\nexport function collapseJsonSuffixModels(\n  models: Model[],\n  services: Service[],\n  webhooks: Webhook[] = [],\n  enums: Enum[] = [],\n  componentNames: ReadonlySet<string> = new Set(),\n): Model[] {\n  const normalizedModels = [...models];\n  const byName = new Map(normalizedModels.map((m) => [m.name, m]));\n\n  // Pass 1: the candidates, each pair on its own, as the document left them.\n  const candidates: FoldCandidate[] = [];\n  for (const model of normalizedModels) {\n    if (!model.name.endsWith('Json')) continue;\n\n    const baseName = model.name.slice(0, -4);\n    const baseModel = byName.get(baseName);\n    if (!baseModel || model.fields.length <= baseModel.fields.length) continue;\n\n    const jsonFields = new Set(model.fields.map((f) => f.name));\n    const isSuperset = baseModel.fields.every((f) => jsonFields.has(f.name));\n    if (!isSuperset) continue;\n\n    // Guard: both models have a const discriminant — they are distinct entities\n    if (hasModelConstDiscriminant(model) && hasModelConstDiscriminant(baseModel)) continue;\n\n    // Guard: a third model explicitly references the Json-suffix model\n    if (isModelReferencedByOthers(model.name, normalizedModels, new Set([model.name, baseName]))) continue;\n\n    // Guard: a live Json model never folds onto a deprecated base — every\n    // live reference to it would then resolve to a deprecated type. (The\n    // other way round still folds: `<Name>` keeps its own, live, flag.)\n    if (baseModel.deprecated && !model.deprecated) {\n      console.warn(\n        `[oagen] Not merging \"${model.name}\" into \"${baseName}\": \"${baseName}\" is deprecated and \"${model.name}\" is live`,\n      );\n      continue;\n    }\n\n    candidates.push({ jsonModel: model, baseModel });\n  }\n\n  // Pass 2: the folds that hold together, decided as a whole.\n  const unionRulesWarning = ({ jsonModel, baseModel }: FoldCandidate): string =>\n    `[oagen] Warning: Json-suffix model \"${jsonModel.name}\" does not preserve the union rules of \"${baseModel.name}\" — keeping both`;\n  const shapeWarning = ({ jsonModel, baseModel }: FoldCandidate, detail: string): string =>\n    `[oagen] Warning: Json-suffix model \"${jsonModel.name}\" does not preserve the shape of \"${baseModel.name}\": ${detail} — keeping both`;\n\n  let accepted = candidates;\n  let read = foldReading(accepted);\n  for (;;) {\n    const readName = read;\n    const options: ShapeReadOptions = { readName };\n    const jsonOf = new Map(accepted.map((candidate) => [candidate.baseModel, candidate.jsonModel]));\n    const shapeOf = (model: Model): Model => {\n      const json = jsonOf.get(model);\n      return json ? foldedShape(model, json) : model;\n    };\n    const refused = new Set<FoldCandidate>();\n    const refuse = (candidate: FoldCandidate, warning: string): void => {\n      if (refused.has(candidate)) return;\n      refused.add(candidate);\n      console.warn(warning);\n    };\n\n    for (const candidate of accepted) {\n      const { jsonModel, baseModel } = candidate;\n\n      // Guard: the base is a union — a named union's variants, composition\n      // keyword and discriminator, or an allOf+oneOf dispatcher's mapping\n      // (such a base may have no fields at all) — that the Json model does\n      // not preserve: it has no variants or rules, or different ones.\n      // Folding would turn the dispatcher into a plain object, or swap its\n      // variants or rules, under operations that already use it (two\n      // undiscriminated unions share the rules `oneOf` while dispatching to\n      // different members). The variants and the mapping's targets are read\n      // under the folds on both sides, so `PetJsonWithName` matches\n      // `PetWithName`, and an inline `PetJsonState` enum matches `PetState`\n      // with the same members and no other; a literal, or a component\n      // enum, as it is. The models the variants name are compared below, as\n      // every folded child is. Identical shapes fold as before.\n      const baseShape = unionShapeKey(baseModel, (v) => typeShapeKey(v, options), { modelName: readName });\n      const jsonShape = unionShapeKey(jsonModel, (v) => typeShapeKey(v, options), { modelName: readName });\n      if (baseShape !== '' && baseShape !== jsonShape) {\n        refuse(candidate, unionRulesWarning(candidate));\n        continue;\n      }\n\n      // Guard: a field both declare must be one the Json model's describes\n      // every value of the base's for (`fieldAdmits`: the same type, limits,\n      // default and flags, the Json model's no stricter on requiredness or\n      // nullability), since the base takes the Json model's fields under\n      // operations that already use it. A field that shares only its name\n      // — `a: integer` beside `a: string`, or required beside optional —\n      // would retype the base, so the fold is refused.\n      const jsonFields = new Map(jsonModel.fields.map((f) => [f.name, f]));\n      const retyped = baseModel.fields.find((f) => !fieldAdmits(jsonFields.get(f.name)!, f, options));\n      if (retyped) refuse(candidate, shapeWarning(candidate, `field \"${retyped.name}\" has a different shape`));\n    }\n\n    // Guard: the models that end under one name. A `<Json>…` child that\n    // collapses — a variant model of the union, a nested object, or any\n    // model spelled that way — must be admitted by the model it collapses\n    // onto (both read under the folds), since the child's references then\n    // resolve to it and a field the child adds would be lost: a variant of\n    // another shape is a different variant even when the fold would give it\n    // the base's name. The flag is read as `modelAdmits` reads it\n    // (`flagAdmits`): a deprecated child collapses onto a live holder, as a\n    // deprecated `<Name>Json` folds onto a live `<Name>`, and a live child\n    // never onto a deprecated one.\n    const folded = new Set(accepted.map((candidate) => candidate.jsonModel));\n    const groups = new Map<string, Model[]>();\n    for (const model of normalizedModels) {\n      if (folded.has(model)) continue;\n      const name = readName(model.name);\n      const group = groups.get(name);\n      if (group) group.push(model);\n      else groups.set(name, [model]);\n    }\n    for (const [name, members] of groups) {\n      if (members.length < 2) continue;\n      const admits = (owner: Model, member: Model): boolean => modelAdmits(shapeOf(owner), shapeOf(member), options);\n      const refuseMember = (member: Model, detail: string): void => {\n        const fold = innermostFold(accepted, member.name)!;\n        refuse(\n          fold,\n          variantModelNames(fold.baseModel, readName).has(name) ? unionRulesWarning(fold) : shapeWarning(fold, detail),\n        );\n      };\n      const holder = members.find((member) => member.name === name);\n      if (holder) {\n        for (const member of members) {\n          if (member !== holder && !admits(holder, member)) {\n            refuseMember(member, `\"${member.name}\" would fold onto \"${name}\", which has a different shape`);\n          }\n        }\n        continue;\n      }\n      const equivalent = (a: Model, b: Model): boolean => admits(a, b) && admits(b, a);\n      for (const member of members) {\n        const other = members.find((candidate) => candidate !== member && !equivalent(member, candidate));\n        if (other) {\n          refuseMember(\n            member,\n            `\"${member.name}\" would fold onto \"${name}\" beside \"${other.name}\", which has a different shape`,\n          );\n        }\n      }\n    }\n\n    if (refused.size === 0) break;\n    accepted = accepted.filter((candidate) => !refused.has(candidate));\n    read = foldReading(accepted);\n  }\n\n  // Apply: shapes, then every reference at once, then names.\n  const renames = new Map<string, string>();\n  for (const model of normalizedModels) {\n    const name = read(model.name);\n    if (name !== model.name) renames.set(model.name, name);\n  }\n  for (const { baseModel, jsonModel } of accepted) applyFold(baseModel, jsonModel);\n  const enumRenames = rewriteModelRefs(normalizedModels, services, renames, webhooks, read);\n\n  const removed = new Set<Model>(accepted.map((candidate) => candidate.jsonModel));\n  // The model that keeps each name: the one the folds leave under it, else\n  // the first declared of those that end under it.\n  const keepers = new Map<string, Model>();\n  for (const model of normalizedModels) {\n    if (removed.has(model)) continue;\n    const name = read(model.name);\n    if (!keepers.has(name) || model.name === name) keepers.set(name, model);\n  }\n  for (const candidate of accepted) {\n    const { jsonModel, baseModel } = candidate;\n    console.warn(\n      `[oagen] Merged \"${jsonModel.name}\" into \"${read(baseModel.name)}\" (${jsonModel.fields.length} fields, superset)`,\n    );\n    // e.g. when AuditLogSchemaJson → AuditLogSchema, also rename\n    // AuditLogSchemaJsonTarget → AuditLogSchemaTarget, or collapse it onto\n    // an AuditLogSchemaTarget that already exists.\n    for (const model of normalizedModels) {\n      if (removed.has(model) || innermostFold(accepted, model.name) !== candidate) continue;\n      const name = read(model.name);\n      if (keepers.get(name) === model) {\n        console.warn(`[oagen] Renamed child \"${jsonModel.name}…\" → \"${name}\"`);\n      } else {\n        removed.add(model);\n        console.warn(`[oagen] Collapsed child \"${model.name}\" into existing \"${name}\"`);\n      }\n    }\n  }\n  for (const model of normalizedModels) if (!removed.has(model)) model.name = read(model.name);\n  const kept = normalizedModels.filter((m) => !removed.has(m));\n\n  // A lifted enum the renames left unreferenced.\n  if (enumRenames.size > 0) {\n    const inPlay = new Set<string>();\n    for (const ref of typeRefsInPlay(kept, services, webhooks)) walkTypeRef(ref, { enum: (r) => inPlay.add(r.name) });\n    for (const [oldName, newName] of enumRenames) {\n      if (componentNames.has(oldName) || inPlay.has(oldName)) continue;\n      const index = enums.findIndex((e) => e.name === oldName);\n      if (index < 0) continue;\n      enums.splice(index, 1);\n      console.warn(`[oagen] Folded enum \"${oldName}\" into \"${newName}\"`);\n    }\n  }\n\n  return kept;\n}\n","import type { Enum, EnumValue, Model, Operation, ResponseHeader, Service, TypeRef, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectModelRefs,\n  collectWebhookTypeRefs,\n} from '../ir/types.js';\nimport { collectInlineEnumFromRef } from './schemas.js';\nimport { enumValuesOf, sameEnumShape } from './enum-members.js';\nimport { isErrorStatusRange, STATUS_RANGE_LABELS } from './responses.js';\n\n/**\n * The step an operation-owned error body's enum takes past a taken name:\n * `<Op>Error<code>` → `<Op>Error<code>Body`, then `…Body2`, `…Body3`, … —\n * numbered under `Body`, the way the error models step in the shape\n * registry (`deferredNamingStem`, kind `error`), so an enum body and an\n * object body in the same spot take the same name (`distinctEnumName`).\n * Every error site passes it, and only an error site (`ownedErrorBodies`);\n * a status code or fallback label qualifies the other sites and numbers on\n * the bare name.\n */\nconst ERROR_BODY_STEP = 'Body';\n\n/**\n * Promote the inline enums a model's fields and named-union variants\n * declare to top-level enums. A field enum is named from its model and field alone\n * (`GetReportResponseStatus`, `ListPetsDefaultResponseStatus`), a name a\n * component enum — or the same field of another model — may already own with\n * other values; such a field is renamed to a distinct name before it is\n * promoted (`…Status2`), collision-aware like the operation pass below and the\n * way header and webhook enums are, so the field never points at the other\n * values. A taken name with the same members — values and per-value\n * deprecation (`sameEnumShape`) — is shared. A name a model owns is a clash\n * too, and the distinct name is never one of `models`' (see\n * `distinctEnumName`): a component field's enum named like a model\n * (`Pet.kind` beside a `PetKind` object) is left on its ref by\n * `extractSchemas` and promoted here as `PetKind2`.\n */\nexport function collectInlineEnumsFromModels(models: Model[], enums: Enum[]): void {\n  const enumNames = new Set(enums.map((e) => e.name));\n  const modelNames = new Set(models.map((model) => model.name));\n  for (const model of models) {\n    for (const ref of collectModelTypeRefs(model)) {\n      collectDistinctEnums(ref, undefined, enums, enumNames, modelNames);\n    }\n  }\n}\n\n/**\n * Collect inline enum definitions from operation parameters (query, path,\n * header, cookie), list-envelope companion fields, response headers, the\n * request body, every success body, error bodies, secondary and fallback\n * response bodies, and secondary request bodies, and promote them to\n * top-level enums so emitters can generate typed enum files.\n *\n * Every kind is collected collision-aware (`collectDistinctEnums`): a\n * parameter enum is named from the service and parameter name alone, so a\n * query parameter `error404` of a later operation derives the very name an\n * earlier operation's inline 404 enum body or `Error404` response header was\n * promoted under (`GetPetError404`), and whichever was collected first would\n * otherwise hand its values to the other's reference. A different value set\n * is renamed to a distinct name before it is promoted (`GetPetError4042`);\n * identical members are shared, as a parameter repeated across the\n * operations of a service always was.\n *\n * `models` lets the walk continue into the models a header or secondary body\n * references — the ones the parser materialized for them, never a component\n * (`componentNames`), whose enums the model pass owns — so an enum nested in\n * such a model gets the same collision-aware treatment as one at the top: a\n * name a component enum already owns with other values is renamed, not\n * silently given the component's values. It is also the set of names a\n * renamed enum must step around (`distinctEnumName`), so pass every model of\n * the document, not only the ones to walk into.\n *\n * `shared` is the parser's record of every type reference a site shared\n * through `components/responses` wrote (`OperationExtractionResult.componentSites`:\n * the component's fallback or error body, a secondary body, a header), by\n * identity — the one record of which sites an operation owns and which a\n * component does. An enum such a site carries is named from the component\n * alone (`CardXMode`, `ProblemResponse`), so on a clash it steps by number\n * (`CardXMode2`, `ProblemResponse2`) — never by the status code, the\n * fallback label (`CardXModeDefault`, `CardXModeClientError`) or `Body`,\n * which qualify an operation's own sites — and every operation that returns\n * the component, at whatever key, settles on the one name. An error site\n * the record does not hold — `errors[].type`, a secondary body of an error\n * entry, a `4XX`/`5XX` range's body or secondary body — is the operation's\n * own, written as `<Op>Error<code>…`, and steps by `Body`\n * (`ownedErrorBodies`). The IR alone cannot tell a shared site from an\n * operation's (`CardXMode` is the name wherever the component is returned),\n * so the record is required: a caller that built `services` by hand passes\n * the references it shares, or an empty set when it declares no component\n * response.\n */\nexport function collectInlineEnumsFromOperations(\n  services: Service[],\n  enums: Enum[],\n  shared: ReadonlySet<TypeRef>,\n  models: readonly Model[] = [],\n  componentNames: ReadonlySet<string> = new Set(),\n): void {\n  // The record moved from the last argument to the third (workos/oagen#356),\n  // so a caller still on the old order hands the models list here and the\n  // record where `componentNames` is read; fail on the mismatch, by name,\n  // rather than inside `models.map` or, worse, silently.\n  if (!(shared instanceof Set)) {\n    throw new TypeError(\n      'collectInlineEnumsFromOperations(services, enums, shared, models?, componentNames?): `shared` must be the Set of ' +\n        `component-site references (\\`OperationExtractionResult.componentSites\\`), got ${describeArgument(shared)}`,\n    );\n  }\n  const enumNames = new Set(enums.map((e) => e.name));\n  const modelsByName = new Map(models.map((model) => [model.name, model]));\n  const modelNames = new Set(modelsByName.keys());\n  // Each materialized model is visited once, under the first qualifier that reaches it.\n  const visited = new Set<string>();\n  const collectThroughModels = (type: TypeRef, qualifier: string | undefined): void => {\n    collectDistinctEnums(type, qualifier, enums, enumNames, modelNames);\n    for (const name of collectModelRefs(type)) {\n      if (visited.has(name) || componentNames.has(name)) continue;\n      visited.add(name);\n      const model = modelsByName.get(name);\n      if (!model) continue;\n      for (const field of model.fields) collectThroughModels(field.type, qualifier);\n    }\n  };\n  for (const service of services) {\n    for (const op of service.operations) {\n      for (const param of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        collectDistinctEnums(param.type, undefined, enums, enumNames, modelNames);\n      }\n      // The iterator's item type is reached through `response` when detection\n      // unwrapped the data array, but an explicit `dataPath` can type it from\n      // the document — an inline enum, or an array or union holding one — on\n      // a body kept as a wrapper, where nothing else references it. It is\n      // walked on its own, like the envelope companions, under the name the\n      // path gave it (`ListPetsRecord`); one a component enum owns with other\n      // members falls back to a numeric suffix. A model it names is walked\n      // like a body's, so an enum nested in one is reached the same way.\n      if (op.pagination) collectThroughModels(op.pagination.itemType, undefined);\n      for (const field of op.pagination?.envelopeFields ?? []) {\n        collectDistinctEnums(field.type, undefined, enums, enumNames, modelNames);\n      }\n      // Response headers are typed like parameters, so an inline enum declared\n      // on one must reach `spec.enums` the same way or the IR would point at\n      // an enum no emitter ever generates. A header a component response\n      // declares (`shared`) carries no status code or fallback label: its\n      // enum steps by number, the same from every site that returns the\n      // component.\n      for (const { headers, qualifier } of responseHeaderGroups(op)) {\n        for (const header of headers) {\n          collectThroughModels(header.type, shared.has(header.type) ? undefined : qualifier);\n        }\n      }\n      // The request body and each success body are typed by `schemaToTypeRef`\n      // under the operation's `<Op>Request` / `<Op>Response` name, so one that\n      // is itself an inline enum, or an array of one, reaches no model and is\n      // promoted here — neither `collectResponseBodyTypes` nor the error loop\n      // below yields it (workos/oagen#281). Every `successResponses` entry is\n      // walked on its own under its status code, as its headers are: the 200\n      // and the 202 derive the same name, so a second body with other members\n      // steps to `CheckPetKindResponse202`, while identical members share. A\n      // lone success response, and the request body, carry no code and fall\n      // back to a numeric suffix (`GetPetKindResponse2`). An enum nested in a\n      // body's model is collected with every other model's\n      // (`collectInlineEnumsFromModels`).\n      for (const { type, qualifier } of requestAndSuccessBodies(op)) {\n        collectDistinctEnums(type, qualifier, enums, enumNames, modelNames);\n      }\n      // An error body that is itself an inline enum, or an array of one, is\n      // typed by `schemaToTypeRef` and reaches no model, so it is promoted\n      // here — after the headers, so a header enum of the same name keeps it\n      // as a header model would. An operation-owned body's name is already\n      // operation-qualified (`GetPetError404`); one a component, header or\n      // earlier error enum owns with other members steps to\n      // `GetPetError404Body`. No inline model holds it: the registry\n      // reserved it before any deferred model was named (`deferredEnumName`\n      // in operations.ts), so an object `404` of another operation under\n      // the same stem is the one that stepped. An enum nested in an error\n      // body's model is collected with every other model's\n      // (`collectInlineEnumsFromModels`). A body a component response\n      // declares (`shared`, so not in `owned`) is the component's, not the\n      // operation's, and steps by number (`CardResponse2`) as it does at a\n      // `default` or range site.\n      const owned = ownedErrorBodies(op, shared);\n      for (const error of op.errors) {\n        if (!error.type) continue;\n        collectDistinctEnums(\n          error.type,\n          owned.has(error.type) ? ERROR_BODY_STEP : undefined,\n          enums,\n          enumNames,\n          modelNames,\n        );\n      }\n      // A body declared only for a secondary media type (`text/plain` next to\n      // `application/json`), or for a `default` or range response, is typed\n      // like a response body, so its inline enums are promoted the same way —\n      // a body that is itself an inline enum, or an array of one, reaches no\n      // model and is walked here; enums nested in its inline models are\n      // reached through them. Its name is already operation-qualified\n      // (`ListPetsDefaultResponse`) or the component's\n      // (`CardApplicationYamlResponse`, `shared`); a clash with a different\n      // value set falls back to a numeric suffix either way — except for an\n      // operation-owned error body (`owned`: a 4xx/5xx or `4XX`/`5XX` body\n      // under a secondary media type, a `4XX`/`5XX` range's body), named\n      // `<Op>Error<code>…` like `errors[].type`, which steps to `…Body` as\n      // that does.\n      for (const { type } of collectResponseBodyTypes(op)) {\n        collectThroughModels(type, owned.has(type) ? ERROR_BODY_STEP : undefined);\n      }\n      // A request body declared only for a secondary media type (`text/csv`\n      // next to `application/json`) is typed like one, with its name already\n      // operation-qualified (`ReplaceWidgetTextCsvRequest`), so its inline\n      // enums are promoted the same way.\n      for (const { type } of collectRequestBodyTypes(op)) {\n        collectThroughModels(type, undefined);\n      }\n    }\n  }\n}\n\n/**\n * Promote the inline enums a webhook declares — on its header, query and\n * cookie parameters, or as its payload itself — to top-level enums, the way\n * response-header enums are: a name already taken by a different value set\n * is not silently shared (the webhook's reference would otherwise point at\n * an unrelated enum's values) but renamed to a distinct one before it is\n * promoted (`PetAdoptedXSource2`); a taken name with the same members is\n * shared, and the distinct name is never one of `models`'\n * (`distinctEnumName`). The parser's stem reservation keeps such a clash from\n * arising through `parseSpec`; this guards the IR for any caller. A payload\n * model's field enums are reached through `spec.models` by\n * `collectInlineEnumsFromModels`, since the model is materialized there.\n */\nexport function collectInlineEnumsFromWebhooks(\n  webhooks: Webhook[],\n  enums: Enum[],\n  models: readonly Model[] = [],\n): void {\n  const enumNames = new Set(enums.map((e) => e.name));\n  const modelNames = new Set(models.map((model) => model.name));\n  for (const webhook of webhooks) {\n    for (const ref of collectWebhookTypeRefs(webhook)) {\n      collectDistinctEnums(ref, undefined, enums, enumNames, modelNames);\n    }\n  }\n}\n\n/** What a misplaced argument is, for the signature error: `an array`, `undefined`, `an object`, … */\nfunction describeArgument(value: unknown): string {\n  if (Array.isArray(value)) return 'an array';\n  if (value === null) return 'null';\n  if (value === undefined) return 'undefined';\n  return `${/^[aeiou]/i.test(typeof value) ? 'an' : 'a'} ${typeof value}`;\n}\n\n/**\n * Every error body of one operation that the operation named itself, by\n * identity: its error sites — each `errors` entry's `type` and secondary\n * bodies, and the body and secondary bodies of each `4XX`/`5XX` range\n * (`isErrorStatusRange`) — less the ones a `components/responses` entry\n * declares (`shared`, `OperationExtractionResult.componentSites`). Each is\n * written as `<Op>Error<code>…` (`GetPetError404`,\n * `GetPetError404ApplicationYaml`, `GetPetError4Xx`), so an enum among them\n * steps by the same `Body` qualifier (`GetPetError4XxBody`); a shared body\n * among those sites is the component's (`ProblemResponse`) and steps by\n * number, as it does at a `default` site, so the one record decides both.\n */\nfunction ownedErrorBodies(op: Operation, shared: ReadonlySet<TypeRef>): ReadonlySet<TypeRef> {\n  const types = new Set<TypeRef>();\n  const own = (type: TypeRef | undefined): void => {\n    if (type && !shared.has(type)) types.add(type);\n  };\n  for (const error of op.errors) {\n    own(error.type);\n    for (const content of error.contents ?? []) own(content.type);\n  }\n  for (const range of op.rangeResponses ?? []) {\n    if (!isErrorStatusRange(range.range)) continue;\n    own(range.type);\n    for (const content of range.contents ?? []) own(content.type);\n  }\n  return types;\n}\n\n/**\n * Header lists to walk, each with the status-code qualifier that keeps a\n * colliding enum name apart. When `successResponses` exists the primary list\n * is the same array as its entry there, so the entries are walked with their\n * own codes instead of `responseHeaders`; a lone 2xx or 3xx response is not\n * listed in `successResponses` (set only for more than one), so its headers\n * get no qualifier — its `responseStatusCode` is deliberately not used here,\n * as qualifying by it would rename every enum such a header declares.\n */\nfunction responseHeaderGroups(op: Operation): Array<{ headers: ResponseHeader[]; qualifier?: string }> {\n  const groups: Array<{ headers: ResponseHeader[]; qualifier?: string }> = [];\n  if (op.successResponses) {\n    for (const entry of op.successResponses) {\n      if (entry.headers) groups.push({ headers: entry.headers, qualifier: String(entry.statusCode) });\n    }\n  } else if (op.responseHeaders) {\n    groups.push({ headers: op.responseHeaders });\n  }\n  for (const error of op.errors) {\n    if (error.headers) groups.push({ headers: error.headers, qualifier: String(error.statusCode) });\n  }\n  // A fallback response has no status code to qualify by; its label\n  // (`Default`, `ClientError`) qualifies its header models and enums, and\n  // names the inline body of a `default` or `1XX`–`3XX` response (a `4XX`\n  // or `5XX` body is named by its range key, `<Op>Error4Xx`).\n  if (op.defaultResponse?.headers) groups.push({ headers: op.defaultResponse.headers, qualifier: 'Default' });\n  for (const range of op.rangeResponses ?? []) {\n    if (range.headers) groups.push({ headers: range.headers, qualifier: STATUS_RANGE_LABELS[range.range] });\n  }\n  return groups;\n}\n\n/**\n * The bodies `collectResponseBodyTypes` leaves out because each is reached\n * through the entry's own `type`: the request body, then every success body,\n * each with the qualifier that keeps a colliding enum name apart. When\n * `successResponses` exists its entries are walked under their own status\n * codes — the primary's `type` is the very ref its entry carries, so\n * `response` is not walked again; a lone 2xx or 3xx response carries no\n * status code in the IR (`successResponses` is set only for more than one),\n * so `response` gets no qualifier, and neither does the request body. Error\n * bodies are walked by the caller under their own qualifier.\n */\nfunction requestAndSuccessBodies(op: Operation): Array<{ type: TypeRef; qualifier?: string }> {\n  const bodies: Array<{ type: TypeRef; qualifier?: string }> = [];\n  if (op.requestBody) bodies.push({ type: op.requestBody });\n  if (op.successResponses) {\n    for (const entry of op.successResponses) bodies.push({ type: entry.type, qualifier: String(entry.statusCode) });\n  } else {\n    bodies.push({ type: op.response });\n  }\n  return bodies;\n}\n\n/**\n * Promote the inline enums under a type reference — a response header's, a\n * secondary media type's or fallback response's body, a webhook parameter's\n * — without letting a taken name mislead. A response-header enum is named\n * from the service and header name alone, so `X-Policy` allowing\n * `fast`/`slow` on a 200 and `retry`/`stop` on a 429 would share one name\n * and whichever was collected first would silently win; a request parameter\n * named like the header, or a webhook parameter named like a component enum,\n * collides the same way. When the name is already taken by a different\n * member set — other values, or the same values with a different one\n * deprecated (`sameEnumShape`) — or by a model, the ref is renamed to a\n * distinct name before it is promoted: an enum and a model under one name\n * reach an emitter as one public symbol, so the name is checked against the\n * union of every model name (`modelNames`, every model of the document) and\n * every enum name (`enums`) before any minted enum keeps it, on every path\n * that promotes one — a field, a parameter, a response header, an error or\n * secondary body, a webhook parameter or payload. A taken name with the same\n * members is shared, as before; the first lifted copy's value descriptions\n * and link are the enum's. A component enum declared under a component\n * model's name is the document's own clash and is left as declared.\n */\nfunction collectDistinctEnums(\n  ref: TypeRef,\n  qualifier: string | undefined,\n  enums: Enum[],\n  enumNames: Set<string>,\n  modelNames: ReadonlySet<string>,\n): void {\n  walkTypeRef(ref, {\n    enum: (ref) => {\n      if (!ref.values) return;\n      const values = enumValuesOf(ref);\n      const existing = enums.find((e) => e.name === ref.name);\n      const ownedByOtherMembers = existing !== undefined && !sameEnumShape(existing.values, values);\n      const ownedByModel = existing === undefined && modelNames.has(ref.name);\n      if (ownedByOtherMembers || ownedByModel) {\n        ref.name = distinctEnumName(ref.name, values, qualifier, enums, modelNames);\n      }\n      collectInlineEnumFromRef(ref, enums, enumNames);\n    },\n  });\n}\n\n/**\n * A name the stem was already stepped to that holds the same members\n * (`isNumericStep`), else the first name not taken by a different member set,\n * nor by a model: the base qualified by the status code\n * (`DocumentsXPolicy429`), then numeric suffixes (`DocumentsXPolicy2`,\n * `DocumentsXPolicy3`, ...). An error body (`ERROR_BODY_STEP`) steps to\n * `GetPetError404Body` and then numbers under it (`GetPetError404Body2`,\n * `GetPetError404Body3`, ...), as the error models do in the shape registry,\n * never on the bare name (`GetPetError4042` is what a parameter named\n * `error404` steps to, a different site). Deterministic for a given spec,\n * since it depends only on declaration order. The collectors\n * run after every model is named, and the merge passes mint against every\n * enum name an `EnumRef` carries (`reservedTypeNames`) — but not against the\n * names chosen here, so this is the side that steps around the other: a\n * model a merge pass qualified to `GetLegacyWidgetWidget2`, because a\n * component enum owns `GetLegacyWidgetWidget`, sends a query enum of that\n * name with other members on to `GetLegacyWidgetWidget3`, and no enum\n * promoted by a collector takes a model's name.\n */\nfunction distinctEnumName(\n  base: string,\n  values: readonly EnumValue[],\n  qualifier: string | undefined,\n  enums: Enum[],\n  modelNames: ReadonlySet<string>,\n): string {\n  const isUsable = (name: string): boolean => {\n    if (modelNames.has(name)) return false;\n    const taken = enums.find((e) => e.name === name);\n    return !taken || sameEnumShape(taken.values, values);\n  };\n  // The stem the numbered steps extend: the bare name, or `<base>Body` for\n  // an error body, whose numbers come under `Body` so an enum body and an\n  // object body past the same two taken names agree (`…Body2`).\n  const stem = qualifier === ERROR_BODY_STEP ? `${base}${qualifier}` : base;\n  // A name this stem already stepped to for the same members — another\n  // status code's body or header (`…200` when this is the 202's), or an\n  // earlier numeric step (`…Body2` for an error body) — is shared before a\n  // new one is minted, so identical members on two status codes never\n  // become two enums once their plain name is taken. Only a digit-qualified\n  // name is a step of this stem: the fallback labels (`…Default`) qualify\n  // other sites, and `…Body` itself is shared through `isUsable` below.\n  const stepped = enums.find(\n    (e) => isNumericStep(e.name, stem) && !modelNames.has(e.name) && sameEnumShape(e.values, values),\n  );\n  if (stepped) return stepped.name;\n  if (qualifier && isUsable(`${base}${qualifier}`)) return `${base}${qualifier}`;\n  let suffix = 2;\n  while (!isUsable(`${stem}${suffix}`)) suffix++;\n  return `${stem}${suffix}`;\n}\n\n/** Whether `name` is `base` followed by one or more digits: a status-code or numeric-suffix step of the stem. */\nfunction isNumericStep(name: string, base: string): boolean {\n  if (name.length <= base.length || !name.startsWith(base)) return false;\n  for (const char of name.slice(base.length)) if (char < '0' || char > '9') return false;\n  return true;\n}\n","import type {\n  ApiSpec,\n  Enum,\n  Model,\n  Operation,\n  Parameter,\n  ParameterGroup,\n  ParameterGroupVariant,\n  Service,\n  TypeRef,\n} from '../ir/types.js';\nimport { enumShapeKey } from './enum-members.js';\nimport { unionShapeKey } from './union-shape.js';\n\n/**\n * Assign `ParameterGroup.wrapperName` across the whole spec.\n *\n * Emitters derive a group's generated wrapper type name from the group name\n * alone, so two operations sharing a group name (create and update both\n * declare `protocol_options`) collapse onto a single type. That is only sound\n * while the two declarations carry the same members. Where they differ, one\n * operation ends up typed with the other's member — e.g. a connection update\n * forced to pass `CreateConnectionSAMLOptions`, which accepts three fields the\n * PATCH endpoint rejects.\n *\n * This pass fingerprints every group's members structurally and qualifies the\n * wrapper name with the operation name only for groups that genuinely diverge.\n * Groups whose declarations agree keep the bare group name, so wrapper types\n * already published in the SDKs are never renamed.\n */\nexport function assignParameterGroupWrapperNames(spec: ApiSpec): void {\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n\n  // group name -> the distinct structural fingerprints seen for it\n  const fingerprints = new Map<string, Set<string>>();\n  const occurrences: Occurrence[] = [];\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      for (const group of op.parameterGroups ?? []) {\n        const fp = fingerprintGroup(group, modelMap, enumMap);\n        let seen = fingerprints.get(group.name);\n        if (!seen) {\n          seen = new Set();\n          fingerprints.set(group.name, seen);\n        }\n        seen.add(fp);\n        occurrences.push({ service, op, group, fingerprint: fp });\n      }\n    }\n  }\n\n  for (const { op, group } of occurrences) {\n    const diverges = (fingerprints.get(group.name)?.size ?? 0) > 1;\n    group.wrapperName = diverges ? `${op.name}_${group.name}` : group.name;\n  }\n\n  qualifyResidualCollisions(occurrences);\n  reconcileSharedGroups(occurrences.map((o) => o.group));\n}\n\ninterface Occurrence {\n  service: Service;\n  op: Operation;\n  group: ParameterGroup;\n  fingerprint: string;\n}\n\n/**\n * Break the collisions the operation-qualified name can still leave behind.\n *\n * `${op.name}_${group.name}` is not a unique key, for two separate reasons:\n *\n *  - `disambiguateOperationNames` makes operation names unique only *within* a\n *    service, so two services that each own an operation named `create`, both\n *    declaring a `password` group with different members, both land on\n *    `create_password`.\n *  - Within one service it deliberately leaves same-name operations alone when\n *    they share a path (see the `uniquePaths.size <= 1` guard — \"same path,\n *    different methods\"), so `PUT` and `PATCH` on one path both stay `update`\n *    and a service prefix alone still produces one name for both.\n *\n * Either way `reconcileSharedGroups` would then fuse two incompatible\n * declarations into a single type — the exact failure this pass exists to\n * prevent — and it does not drop the surplus member, so the wrapper would\n * expose a field one of the operations rejects.\n *\n * So escalate in rounds, adding a qualifier at a time and re-testing what still\n * collides. `(service, path, method)` identifies an operation uniquely, and a\n * same-name collision within a service implies a shared path, so service then\n * method is sufficient to separate every case.\n *\n * Each round only touches names that *still* group differing fingerprints, so a\n * name whose sharers agree is never renamed: sharing one wrapper is exactly what\n * should happen there, and renaming it would move a type the SDKs already\n * publish. On a spec where no qualified name collides — the WorkOS spec today —\n * the whole pass is a no-op.\n */\nfunction qualifyResidualCollisions(occurrences: Occurrence[]): void {\n  // Prepended in order, matching how the operation and group names already\n  // compose, so a fully-escalated name reads `<method>_<service>_<op>_<group>`.\n  const qualifiers: ((o: Occurrence) => string)[] = [(o) => o.service.name, (o) => o.op.httpMethod];\n\n  for (const qualify of qualifiers) {\n    for (const sharers of collidingCandidates(occurrences)) {\n      // A declaration still holding its group's own bare name owns that name.\n      // A qualified name can land on some *other* group's literal name — an\n      // `update` operation's `parent` group qualifies to `update_parent`, which\n      // may already be a group called `update_parent` — and that group is\n      // internally consistent, never diverged, and already published under it.\n      // Move only the declarations that have already been escalated; anything\n      // left fused falls through to the terminal round.\n      //\n      // This cannot strand a collision. Two groups sharing a literal name with\n      // differing structures always diverge on that name and are both qualified\n      // in the first assignment, so at most one member of a colliding set can\n      // still be bare. When one is, moving the rest separates them; in the\n      // degenerate case where none are movable, nothing moves here and the\n      // terminal round separates by structure regardless.\n      const movable = sharers.filter((o) => o.group.wrapperName !== o.group.name);\n      for (const o of movable) {\n        o.group.wrapperName = `${qualify(o)}_${o.group.wrapperName ?? o.group.name}`;\n      }\n    }\n  }\n\n  separateRemainingByStructure(occurrences);\n}\n\n/**\n * Terminal round: separate whatever the operation attributes could not.\n *\n * No combination of operation attributes is unique by construction. Two\n * operations in one service can share a name, a method *and* differ only by\n * path — `normalizeOperationIdForNaming` strips the `[N]` suffix, so a NestJS\n * controller method bound to several routes derives one name for all of them.\n * The WorkOS spec already contains such a pair (`Authorization`'s\n * `listRoleAssignments` on two paths); it declares no parameter groups today,\n * so nothing is wrong in the SDKs, but the shape is present rather than\n * hypothetical. Adding `path` as a fourth qualifier would only move the\n * boundary again.\n *\n * So stop enumerating attributes and separate by the thing that actually\n * matters: a name still fusing distinct structures gets one wrapper per\n * distinct fingerprint. That makes \"same `wrapperName` implies same structure\"\n * hold unconditionally, which is the invariant every emitter relies on.\n *\n * Suffixes are keyed on the fingerprint, not on a per-occurrence counter, so\n * declarations that agree keep sharing a wrapper.\n *\n * Ordering is by first appearance, not by sorted fingerprint: the structure\n * declared first keeps the unsuffixed name. Sorting by fingerprint would be\n * equally deterministic but less stable in the way that matters — adding a\n * member to one operation changes its fingerprint and could swap which of two\n * published wrappers holds the bare name. Under first-appearance order only\n * reordering the operations themselves can shift a name, which is both rarer\n * and visible in the spec diff.\n *\n * Either way this is a no-op wherever an earlier round already sufficed —\n * including the WorkOS spec, which never reaches this round at all.\n */\nfunction separateRemainingByStructure(occurrences: Occurrence[]): void {\n  const taken = new Set(occurrences.map((o) => o.group.wrapperName ?? o.group.name));\n\n  for (const sharers of collidingCandidates(occurrences)) {\n    const base = sharers[0].group.wrapperName ?? sharers[0].group.name;\n\n    // First fingerprint seen keeps `base`; each new one takes the next free\n    // `base_N`, skipping any name already spoken for elsewhere in the spec.\n    const nameFor = new Map<string, string>();\n    let n = 2;\n    for (const o of sharers) {\n      if (nameFor.has(o.fingerprint)) continue;\n      if (nameFor.size === 0) {\n        nameFor.set(o.fingerprint, base);\n        continue;\n      }\n      while (taken.has(`${base}_${n}`)) n++;\n      const name = `${base}_${n}`;\n      taken.add(name);\n      nameFor.set(o.fingerprint, name);\n      n++;\n    }\n\n    for (const o of sharers) o.group.wrapperName = nameFor.get(o.fingerprint)!;\n  }\n}\n\n/**\n * Candidate wrapper names shared by declarations that do not agree — the only\n * ones an escalation round may rename.\n */\nfunction collidingCandidates(occurrences: Occurrence[]): Occurrence[][] {\n  const byCandidate = new Map<string, Occurrence[]>();\n  for (const o of occurrences) {\n    const key = o.group.wrapperName ?? o.group.name;\n    const list = byCandidate.get(key);\n    if (list) list.push(o);\n    else byCandidate.set(key, [o]);\n  }\n  return [...byCandidate.values()].filter(\n    (sharers) => sharers.length > 1 && new Set(sharers.map((o) => o.fingerprint)).size > 1,\n  );\n}\n\n/**\n * Make every group that shares a `wrapperName` describe literally the same\n * type.\n *\n * Deciding two declarations may share one wrapper is only half the job. The\n * fingerprint deliberately ignores nullability and member order, so sharers can\n * still disagree on both — and each emitter renders the wrapper from whichever\n * operation it happens to reach first while rendering call sites from their own\n * operation. Kotlin showed the consequence: `ParentResource.ById.id` emitted as\n * `String` from one operation, while the Java-friendly overload built from\n * another passed a `String?` into it, and the SDK stopped compiling.\n *\n * So normalize the two axes the fingerprint waived:\n *   - a member the sharers disagree on settles as non-nullable. Widening to\n *     nullable instead reads as the friendlier choice, but the nullable form\n *     doesn't survive every emitter's group paths (Kotlin's query dispatch\n *     builds a `Pair<String, String>` from the member, which a `String?` can't\n *     satisfy), and non-nullable is what all sharers carried before group\n *     member types were resolved at all — so it changes no published surface.\n *     A member every sharer agrees is nullable stays nullable.\n *\n *     The cost: an operation whose spec really does accept null for a member\n *     (`PATCH` on a resource may clear `parent_resource_id`) can't express that\n *     through the shared wrapper. It never could — the member used to be a flat\n *     `string` everywhere — so nothing regresses, but the limitation is real and\n *     removing it means letting that group's wrapper split per operation.\n *   - member order follows the first sharer, so positional constructors and\n *     their call sites agree.\n */\nfunction reconcileSharedGroups(groups: ParameterGroup[]): void {\n  const byWrapper = new Map<string, ParameterGroup[]>();\n  for (const group of groups) {\n    const key = group.wrapperName ?? group.name;\n    const list = byWrapper.get(key);\n    if (list) list.push(group);\n    else byWrapper.set(key, [group]);\n  }\n\n  for (const sharers of byWrapper.values()) {\n    if (sharers.length < 2) continue;\n\n    for (const variant of sharers[0].variants) {\n      const peers = sharers\n        .slice(1)\n        .map((g) => g.variants.find((v) => v.name === variant.name))\n        .filter((v): v is ParameterGroupVariant => v !== undefined);\n      if (peers.length === 0) continue;\n\n      // Settle nullability: unanimously-nullable members stay nullable, and any\n      // member the sharers disagree on drops to non-nullable in all of them.\n      for (const member of variant.parameters) {\n        const all = [member, ...peers.map((p) => p.parameters.find((q) => q.name === member.name)).filter(isParameter)];\n        if (all.every((p) => p.type.kind === 'nullable')) continue;\n        for (const p of all) {\n          if (p.type.kind === 'nullable') p.type = p.type.inner;\n        }\n      }\n\n      // Align order on the first sharer's, leaving any member it doesn't\n      // declare in place at the end rather than dropping it.\n      const canonical = variant.parameters.map((p) => p.name);\n      for (const peer of peers) {\n        peer.parameters.sort((a, b) => {\n          const ia = canonical.indexOf(a.name);\n          const ib = canonical.indexOf(b.name);\n          if (ia === -1 && ib === -1) return 0;\n          if (ia === -1) return 1;\n          if (ib === -1) return -1;\n          return ia - ib;\n        });\n      }\n    }\n  }\n}\n\nfunction isParameter(p: Parameter | undefined): p is Parameter {\n  return p !== undefined;\n}\n\n/**\n * Structural fingerprint of a group: its variants, their members, and each\n * member's resolved shape. Two declarations with the same fingerprint can\n * safely share one generated wrapper type.\n */\nfunction fingerprintGroup(group: ParameterGroup, modelMap: Map<string, Model>, enumMap: Map<string, Enum>): string {\n  const variants = group.variants.map((v) => {\n    // Members are sorted by name: every emitter renders the wrapper as a\n    // named-field type (dataclass, data class, readonly promoted properties,\n    // struct variant), so two operations listing the same members in a\n    // different order still describe the same type and must keep sharing one\n    // wrapper rather than being renamed apart.\n    const members = [...v.parameters]\n      .sort((a, b) => a.name.localeCompare(b.name))\n      .map((p) => `${p.name}:${fingerprintType(p.type, modelMap, enumMap, new Set())}`);\n    const optional = [...(v.optionalParameters ?? [])].sort();\n    return `${v.name}(${members.join(',')})[${optional.join(',')}]`;\n  });\n  // `optional` is deliberately excluded: whether the group as a whole may be\n  // omitted is a property of the operation's signature, not of the wrapper\n  // type, and create/update legitimately differ there (required vs optional)\n  // while sharing an identical wrapper.\n  return variants.join('|');\n}\n\n/**\n * Fingerprint a type by shape rather than by name.\n *\n * Names cannot be compared directly because the parser synthesizes a separate\n * name per declaration site for inline schemas: `create_user` and `update_user`\n * each get their own `PasswordHashType` enum, spelled `CreateUserPasswordHashType`\n * and `UpdateUserPasswordHashType`, though their values are identical. Comparing\n * names would report divergence and rename a wrapper for no reason.\n *\n * Nullability is also stripped: an update declaring a member nullable while\n * create declares it plain is not a reason to split the wrapper type.\n */\nfunction fingerprintType(\n  ref: TypeRef,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n  visiting: Set<string>,\n): string {\n  switch (ref.kind) {\n    case 'nullable':\n      // Widening only — a nullable and a non-nullable member are compatible.\n      return fingerprintType(ref.inner, modelMap, enumMap, visiting);\n    case 'primitive':\n      return `p:${ref.type}`;\n    case 'literal':\n      return `l:${typeof ref.value}:${String(ref.value)}`;\n    case 'array':\n      return `a<${fingerprintType(ref.items, modelMap, enumMap, visiting)}>`;\n    case 'map':\n      return `m<${fingerprintType(ref.valueType, modelMap, enumMap, visiting)}>`;\n    case 'union':\n      // Sorted, like enum values and model fields: a union accepts the same set\n      // of types whichever order the branches are written in, so two operations\n      // listing equivalent branches differently describe the same type and must\n      // keep sharing a wrapper rather than renaming a published one apart.\n      return `u<${ref.variants\n        .map((v) => fingerprintType(v, modelMap, enumMap, visiting))\n        .sort()\n        .join(',')}>`;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      if (!e) return `e:${ref.name}`;\n      // Values, not the synthesized name — two inline copies of one enum are\n      // the same type for wrapper-sharing purposes. The value's primitive type\n      // is part of the fingerprint (as it is for `literal`): the IR keeps\n      // numeric `5` and string `\"5\"` distinct, and so do the emitters, so two\n      // enums that stringify alike are still different types. So is each\n      // value's deprecation (`enumShapeKey`): a copy that deprecates a value\n      // the other does not is a different type, as a deprecated model is\n      // from a live one.\n      //\n      // Sorted, like model fields and group members above: declaration order of\n      // enum values does not change which values the member accepts, so two\n      // inline enums listing one set in different orders must keep sharing a\n      // wrapper rather than renaming an already-published type apart.\n      return `e<${enumShapeKey(e.values)}>`;\n    }\n    case 'model': {\n      const m = modelMap.get(ref.name);\n      if (!m) return `M:${ref.name}`;\n      // Recursion guard: a model reachable from itself fingerprints by name at\n      // the point of recurrence, which is enough to distinguish shapes.\n      if (visiting.has(ref.name)) return `M:${ref.name}`;\n      const next = new Set(visiting).add(ref.name);\n      const fields = [...m.fields]\n        .sort((a, b) => a.name.localeCompare(b.name))\n        .map((f) => `${f.name}${f.required ? '!' : '?'}:${fingerprintType(f.type, modelMap, enumMap, next)}`);\n      // A named union's variants are its shape too — sorted like a union\n      // TypeRef's, since order does not change what it accepts — and so are\n      // its dispatch rules: two unions with the same members but different\n      // discriminators are different member types and must not share a\n      // wrapper.\n      return `M<${fields.join(',')}>${unionShapeKey(m, (v) => fingerprintType(v, modelMap, enumMap, next), { sorted: true })}`;\n    }\n    default:\n      return 'unknown';\n  }\n}\n","import type { ApiSpec, TypeRef } from '../ir/types.js';\nimport { walkTypeRef, collectResponseHeaders, collectRequestBodyTypes, collectResponseBodyTypes } from '../ir/types.js';\n\nexport function validateModelRefs(spec: ApiSpec): void {\n  const knownNames = new Set<string>();\n  for (const m of spec.models) knownNames.add(m.name);\n  for (const e of spec.enums) knownNames.add(e.name);\n\n  function walkRef(ref: TypeRef, context: string): void {\n    walkTypeRef(ref, {\n      model: (r) => {\n        if (!knownNames.has(r.name)) {\n          console.warn(`[oagen] Warning: Unresolved model reference \"${r.name}\" (context: ${context})`);\n        }\n      },\n    });\n  }\n\n  for (const model of spec.models) {\n    for (const field of model.fields) {\n      walkRef(field.type, `${model.name}.${field.name}`);\n    }\n    for (const variant of model.variants ?? []) {\n      walkRef(variant, `${model.name}.variants`);\n    }\n  }\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      for (const p of [...op.pathParams, ...op.queryParams, ...(op.bodyOwnedQueryParams ?? []), ...op.headerParams]) {\n        walkRef(p.type, `${service.name}.${op.name}.${p.name}`);\n      }\n      if (op.requestBody) walkRef(op.requestBody, `${service.name}.${op.name}.requestBody`);\n      walkRef(op.response, `${service.name}.${op.name}.response`);\n      if (op.pagination) walkRef(op.pagination.itemType, `${service.name}.${op.name}.pagination.itemType`);\n      for (const field of op.pagination?.envelopeFields ?? []) {\n        walkRef(field.type, `${service.name}.${op.name}.pagination.${field.name}`);\n      }\n      for (const error of op.errors) {\n        if (error.type) walkRef(error.type, `${service.name}.${op.name}.errors.${error.statusCode}`);\n      }\n      for (const header of collectResponseHeaders(op)) {\n        walkRef(header.type, `${service.name}.${op.name}.headers.${header.name}`);\n      }\n      for (const { type, source } of collectResponseBodyTypes(op)) {\n        walkRef(type, `${service.name}.${op.name}.${source}`);\n      }\n      for (const { type, source } of collectRequestBodyTypes(op)) {\n        walkRef(type, `${service.name}.${op.name}.${source}`);\n      }\n    }\n  }\n\n  for (const webhook of spec.webhooks ?? []) {\n    const context = `webhooks.${webhook.name}.${webhook.httpMethod}`;\n    for (const p of [...webhook.headerParams, ...webhook.queryParams, ...(webhook.cookieParams ?? [])]) {\n      walkRef(p.type, `${context}.${p.name}`);\n    }\n    if (webhook.requestBody) walkRef(webhook.requestBody, `${context}.requestBody`);\n    // The payload of every other media type, which shares no reference with `requestBody`.\n    for (const content of webhook.requestBodyContents ?? []) {\n      if (content.type !== webhook.requestBody) {\n        walkRef(content.type, `${context}.requestBodyContents.${content.contentType}`);\n      }\n    }\n  }\n}\n","/**\n * Collapse the models the parser materializes for inline error bodies onto a\n * handful of shared models named by shape.\n *\n * Since workos/oagen#243 every inline 4xx/5xx body is a model of its own,\n * `<Op>Error<code>` (#356), and two bodies share a model only when their\n * fingerprints agree — fields, types, every `const` and every description.\n * A document that writes its errors inline, one schema per error code, as a\n * generator such as NestJS does, declares hundreds of them: the WorkOS\n * document has 834 inline error bodies in 13 shapes, 433 of them\n * `{ message }` and 344 `{ code: <const>, message }`, and no SDK runtime\n * reads a single one of the 834 models — they reach a consumer as files,\n * barrel exports and round-trip tests only. Every emitter also writes the\n * models an operation references from `errors[].type`, so the per-operation\n * names (`ConnectionCreateError4222`, `WebhookEndpointsDeleteError404 =\n * DataIntegrationsUpsertApiKeyError404`) are what a reader of the SDK sees.\n *\n * This pass runs once the operations' models are merged and before the\n * inline-enum collectors (`parseSpec`). It reads every error site — each\n * `errors[]` entry's `type` and its secondary `contents[].type`, and the body\n * and secondary bodies of a `4XX`/`5XX` range — and takes the models only\n * those sites reach (`errorOnly`): a component schema, a model a success\n * body, parameter, header, webhook or component also reaches, and a body a\n * `components/responses` entry declares (`componentSites`) are left exactly\n * as they are. The models it takes are keyed by structure alone\n * (`ModelKeys`): field names, requiredness, flags and types, a nested\n * error-only model by its own key, and a string the document pins —\n * `const: idp_metadata_fetch_failed`, an inline `enum`, a plain `string` —\n * all as one string, so the bodies that differ only in their error code,\n * their prose or their `x-` extensions fold onto one model. A string inside\n * an array, union or map keeps its value in the key, and so does a field's\n * `domainName` (a `fieldHints` entry), so neither is lost in a fold.\n *\n * Each group becomes one model, named from its shape alone (`bodyName`):\n * `ErrorBody` for `{ message }`, `OAuthErrorBody` for the OAuth error format\n * `{ error, error_description }`, else the base plus `With` and a token per\n * further field. A field's token is its name in PascalCase, qualified by what\n * its type adds so that two shapes with the same field names still read\n * apart: an array of strings is `MessageList`, a union joins its variants\n * with `Or` (`MessageOrMessageList`), and a nested error body is prefixed\n * with the field names of its own (`ErrorBodyWithCodeFieldErrors` for\n * `{ message, errors: [{ code, field }] }`). A group whose members all pin\n * one string field to one value is named from that value instead\n * (`RateLimitExceededErrorBody`, `InvalidGrantOAuthErrorBody`; the field's\n * name follows the value unless it is `code` or `error`), plus `With` and\n * the plain names of any further fields\n * (`OrganizationSelectionRequiredErrorBodyWithOrganizations`). A model only\n * another error body reaches is named from its parent and field\n * (`OrganizationSelectionRequiredErrorBodyWithOrganization`, singular for an\n * array item). `ErrorBody` rather than `ErrorResponse` because an emitter\n * may already spend that name on a component called `Error` (Go does).\n *\n * The pass never numbers a name. A shared name a component schema of exactly\n * that shape already holds — one whose string fields admit every value the\n * bodies pin — is that component: the group folds onto it. A name anything\n * else holds — a component of another shape, an enum, a shared\n * body of another shape — leaves the group's models exactly as the parser\n * materialized them, with every error-only model they reach or are reached\n * from, and says so in a warning naming both sides; the fold then runs\n * again without them, since a freed name may now suit another group.\n *\n * A string field a group pins to two or more values becomes an enum shared by\n * every error body that has a field of that name — `ErrorBodyCode` for\n * `code`, `ErrorBodyError` for an OAuth `error` — holding every value any\n * error body pins that field to, which the collectors lift as they lift any\n * inline enum (an emitter's enums admit an unlisted value, and the field's\n * prose says more may come). An enum of that name the document already holds\n * is shared when the members agree; when they do not, or a model holds the\n * name, the fields stay plain strings, with a warning. One value every\n * member pins stays that literal, and a lone pinned value beside free\n * strings widens to `string`. A field's\n * description, example and extensions survive only when every member wrote\n * the same one; the response's own `description` stays on the `errors[]`\n * entry, where it always was.\n *\n * The references are rewritten in place, so the `contents` entry that shared\n * its `type` with the entry's `type` keeps sharing it. A `oneOf` of variants\n * that fold onto one model is no longer a union: duplicate variants are\n * dropped and a lone survivor replaces the union. The models the pass folds\n * are removed; the shared ones join the list.\n *\n * `collapseErrorBodies: false` on `ParseOptions` keeps the per-operation\n * models for a consumer that names them.\n */\nimport type { Enum, EnumRef, Field, Model, Service, TypeRef, UnionType, Webhook } from '../ir/types.js';\nimport {\n  collectModelRefs,\n  collectModelTypeRefs,\n  collectOperationTypeRefs,\n  collectWebhookTypeRefs,\n  renameTypeRefModels,\n} from '../ir/types.js';\nimport { singularize, toPascalCase } from '../utils/naming.js';\nimport { sameEnumShape } from './enum-members.js';\nimport { isErrorStatusRange } from './responses.js';\n\n/** The stem every shared error body is named from: `ErrorBody`, `ErrorBodyWithCode`, and the enums `ErrorBodyCode`, `ErrorBodyError`. */\nexport const ERROR_BODY_BASE = 'ErrorBody';\n\nexport interface CollapseErrorBodiesInput {\n  services: Service[];\n  webhooks?: readonly Webhook[];\n  models: Model[];\n}\n\nexport interface CollapseErrorBodiesOptions {\n  /** The document's component schema names (after `schemaNameTransform`): never folded, and whatever they reach stays. */\n  componentNames: ReadonlySet<string>;\n  /**\n   * Type references a `components/responses` entry wrote\n   * (`OperationExtractionResult.componentSites`): the component's body is\n   * the component's, named after it, and is left alone.\n   */\n  componentSites?: ReadonlySet<TypeRef>;\n  /**\n   * The document's enums and every enum lifted before the pass. No shared\n   * model takes one of their names (bodies whose shared name an `ErrorBody`\n   * enum a component's `body` field minted would take are left as they\n   * are), and a shared enum takes the name of one of them only when the\n   * members agree, sharing it as the collectors share any inline enum.\n   */\n  enums?: readonly Enum[];\n}\n\n/**\n * Where an error body's type is read and written back: an `errors[]` entry's\n * `type`, each of its `contents[].type`, and the same two on a `4XX`/`5XX`\n * range. Held as accessors so a union a fold turns into one reference can be\n * replaced at every site that held the union object.\n */\ninterface ErrorSlot {\n  get(): TypeRef | undefined;\n  set(type: TypeRef): void;\n}\n\n/** What a group's members pin a string field to: every `const` or inline `enum` value, and whether any member leaves it a plain string. */\ninterface PinnedValues {\n  values: Set<string>;\n  open: boolean;\n}\n\n/**\n * Fold the error-only models of `input.models` onto shared, shape-named\n * models; rewrite every error site of `input.services` to reference them;\n * and return the model list with the folded models removed and the shared\n * ones appended. The services are mutated in place; `input.models` is not.\n */\nexport function collapseErrorBodies(input: CollapseErrorBodiesInput, options: CollapseErrorBodiesOptions): Model[] {\n  const operations = input.services.flatMap((service) => service.operations);\n  const componentSites = options.componentSites ?? new Set<TypeRef>();\n  const slots = errorSlots(operations).filter((slot) => {\n    const type = slot.get();\n    return type !== undefined && !componentSites.has(type);\n  });\n  if (slots.length === 0) return input.models;\n\n  const byName = new Map(input.models.map((model) => [model.name, model]));\n  const slotTypes = new Set(slots.map((slot) => slot.get()!));\n\n  // Everything a non-error site reaches is kept: the components and what\n  // they reach, every parameter, request body, success, default and\n  // non-error range body, every header (an error's headers included — a\n  // header is not a body), every webhook, and every component response site.\n  const keepRoots: string[] = [...options.componentNames];\n  for (const op of operations) {\n    for (const ref of collectOperationTypeRefs(op)) if (!slotTypes.has(ref)) keepRoots.push(...collectModelRefs(ref));\n  }\n  for (const webhook of input.webhooks ?? []) {\n    for (const ref of collectWebhookTypeRefs(webhook)) keepRoots.push(...collectModelRefs(ref));\n  }\n  for (const ref of componentSites) keepRoots.push(...collectModelRefs(ref));\n  const kept = closure(keepRoots, byName);\n\n  const errorRoots = [...slotTypes].flatMap((type) => collectModelRefs(type));\n  const errorOnly = new Set(\n    [...closure(errorRoots, byName)].filter(\n      (name) => !kept.has(name) && !options.componentNames.has(name) && byName.has(name),\n    ),\n  );\n  if (errorOnly.size === 0) return input.models;\n\n  // A group whose shared name something of another shape already holds is\n  // left as it is, with every error-only model it reaches or is reached\n  // from, and the fold is retried without them: a name that group had taken\n  // may suit another.\n  let candidates: ReadonlySet<string> = errorOnly;\n  for (;;) {\n    const outcome = fold(candidates, { input, options, byName, slots, errorRoots });\n    if (outcome.frozen.size === 0) return outcome.models;\n    candidates = new Set([...candidates].filter((name) => !outcome.frozen.has(name)));\n    if (candidates.size === 0) return input.models;\n  }\n}\n\ninterface FoldContext {\n  input: CollapseErrorBodiesInput;\n  options: CollapseErrorBodiesOptions;\n  byName: ReadonlyMap<string, Model>;\n  slots: readonly ErrorSlot[];\n  /** The model names every error site references directly. */\n  errorRoots: readonly string[];\n}\n\n/**\n * One attempt at folding the error-only models `errorOnly`: the model list\n * with every group folded, or — when a shared name is taken by something of\n * another shape — the names of the models to leave as they are, so the\n * caller can try again without them.\n */\nfunction fold(\n  errorOnly: ReadonlySet<string>,\n  { input, options, byName, slots, errorRoots }: FoldContext,\n): { models: Model[]; frozen: ReadonlySet<string> } {\n  // Group by structure, each group's members in name order.\n  const keys = new ModelKeys(errorOnly, byName);\n  const groups = new Map<string, Model[]>();\n  for (const name of [...errorOnly].sort()) {\n    const key = keys.of(name);\n    const group = groups.get(key);\n    if (group) group.push(byName.get(name)!);\n    else groups.set(key, [byName.get(name)!]);\n  }\n  // Groups are ordered by shape, never by the operations that produced them:\n  // fewer fields first, then the key, so when two shapes ask for one name the\n  // same one keeps it whichever operation declared it, and renaming an\n  // operation moves no model name.\n  const orderedGroups = [...groups.entries()].sort(([keyA, a], [keyB, b]) => {\n    const fields = a[0].fields.length - b[0].fields.length;\n    return fields !== 0 ? fields : keyA < keyB ? -1 : keyA > keyB ? 1 : 0;\n  });\n  const pinnedByKey = new Map<string, Map<string, PinnedValues>>();\n  for (const [key, members] of orderedGroups) pinnedByKey.set(key, pinnedValues(members));\n\n  // The values every error body pins a field of one name to, across every\n  // group: the members of the shared enum that field becomes.\n  const enumValuesByField = new Map<string, Set<string>>();\n  for (const pinned of pinnedByKey.values()) {\n    for (const [field, { values }] of pinned) {\n      const all = enumValuesByField.get(field) ?? new Set<string>();\n      for (const value of values) all.add(value);\n      enumValuesByField.set(field, all);\n    }\n  }\n\n  // Name the groups: the ones an error site references directly first, from\n  // their pinned value or their fields; then the ones only another error\n  // body reaches, from their parent and field.\n  const topLevel = new Set(errorRoots.filter((name) => errorOnly.has(name)));\n  const existingEnums = options.enums ?? [];\n  // Who holds each name a shared model or enum might take.\n  const holders = new Map<string, string>();\n  for (const model of input.models) if (!errorOnly.has(model.name)) holders.set(model.name, `model \"${model.name}\"`);\n  for (const name of options.componentNames) holders.set(name, `component schema \"${name}\"`);\n  for (const e of existingEnums) holders.set(e.name, `enum \"${e.name}\"`);\n  const canonical = new Map<string, string>(); // group key → shared name\n  const absorbed = new Set<string>(); // group keys folded onto a component of their shape\n  const seeds = new Set<string>(); // the models of the groups left as they are\n  const claim = (name: string, key: string, members: readonly Model[]): void => {\n    const holder = holders.get(name);\n    if (holder === undefined) {\n      holders.set(name, `the shared error body \"${name}\" ${shapeOf(members[0])}`);\n      canonical.set(key, name);\n      return;\n    }\n    // A component schema of exactly this shape, admitting every value the\n    // bodies pin, is the shared body.\n    const component = byName.get(name);\n    if (\n      component &&\n      !errorOnly.has(name) &&\n      keys.of(name) === key &&\n      componentAccepts(component, pinnedByKey.get(key)!)\n    ) {\n      canonical.set(key, name);\n      absorbed.add(key);\n      return;\n    }\n    for (const member of members) seeds.add(member.name);\n    const list = members.map((member) => `\"${member.name}\"`).join(', ');\n    const kept = members.length === 1 ? `model ${list} as it is` : `models ${list} as they are`;\n    console.warn(\n      `[oagen] Warning: The shared error body ${shapeOf(members[0])} would be named \"${name}\", which ${holder} already holds — keeping ${kept}; give the two the same shape, or rename one`,\n    );\n  };\n  const frozenOut = (members: readonly Model[]): boolean => members.some((member) => seeds.has(member.name));\n  for (const [key, members] of orderedGroups) {\n    if (!members.some((member) => topLevel.has(member.name))) continue;\n    claim(bodyName(members[0], pinnedByKey.get(key)!, errorOnly, byName), key, members);\n  }\n  // Every (parent, field) that reaches a nested error-only model, read on\n  // the models before the fold.\n  const parentsOf = new Map<string, Array<{ parent: Model; field: Field }>>();\n  for (const name of errorOnly) {\n    const model = byName.get(name)!;\n    for (const field of model.fields) {\n      for (const child of collectModelRefs(field.type)) {\n        if (!errorOnly.has(child) || child === name) continue;\n        const list = parentsOf.get(child) ?? [];\n        list.push({ parent: model, field });\n        parentsOf.set(child, list);\n      }\n    }\n  }\n  for (let progressed = true; progressed;) {\n    progressed = false;\n    for (const [key, members] of orderedGroups) {\n      if (canonical.has(key) || frozenOut(members)) continue;\n      const candidates = members\n        .flatMap((member) => parentsOf.get(member.name) ?? [])\n        .map(({ parent, field }) => {\n          const parentName = canonical.get(keys.of(parent.name));\n          return parentName === undefined ? undefined : nestedName(parentName, field);\n        })\n        .filter((candidate): candidate is string => candidate !== undefined)\n        .sort();\n      if (candidates.length === 0) continue;\n      claim(candidates[0], key, members);\n      progressed = true;\n    }\n  }\n  // A group nothing named reaches — only through a cycle among error bodies,\n  // or through a group left as it is — is named from its own fields.\n  for (const [key, members] of orderedGroups) {\n    if (!canonical.has(key) && !frozenOut(members)) {\n      claim(bodyName(members[0], pinnedByKey.get(key)!, errorOnly, byName), key, members);\n    }\n  }\n  if (seeds.size > 0) {\n    // A model left as it is keeps its fields, so everything it reaches stays\n    // too; and a shared parent would reference one member's child and strand\n    // the others', so everything that reaches a frozen model stays as well.\n    const errorOnlyClosure = (roots: readonly string[]): string[] =>\n      [...closure(roots, byName)].filter((name) => errorOnly.has(name));\n    const frozen = new Set(errorOnlyClosure([...seeds]));\n    for (let grew = true; grew;) {\n      grew = false;\n      for (const name of errorOnly) {\n        if (frozen.has(name)) continue;\n        const reached = errorOnlyClosure([name]);\n        if (reached.some((other) => frozen.has(other))) {\n          for (const other of reached) frozen.add(other);\n          grew = true;\n        }\n      }\n    }\n    return { models: input.models, frozen };\n  }\n\n  // The shared enums, one per field name some group pins to two or more\n  // values, named from the same pool as the models so neither takes the\n  // other's name; a field whose enum name is taken stays a plain string.\n  const enumNamesByField = new Map<string, string>();\n  const widened = new Set<string>();\n  for (const [key] of orderedGroups) {\n    if (absorbed.has(key)) continue;\n    for (const [field, { values }] of pinnedByKey.get(key)!) {\n      if (values.size < 2 || enumNamesByField.has(field) || widened.has(field)) continue;\n      const base = `${ERROR_BODY_BASE}${toPascalCase(field)}`;\n      const members = [...(enumValuesByField.get(field) ?? values)].sort().map((value) => ({ name: value, value }));\n      // An enum of that name with the same members is shared, as the\n      // collectors share any inline enum.\n      const shared = existingEnums.find((e) => e.name === base && sameEnumShape(e.values, members));\n      if (shared) {\n        enumNamesByField.set(field, shared.name);\n        continue;\n      }\n      const holder = holders.get(base);\n      if (holder === undefined) {\n        holders.set(base, `the shared enum \"${base}\"`);\n        enumNamesByField.set(field, base);\n        continue;\n      }\n      widened.add(field);\n      console.warn(\n        `[oagen] Warning: The values error bodies pin \"${field}\" to would be the shared enum \"${base}\", which ${holder} already holds — keeping those fields plain strings`,\n      );\n    }\n  }\n\n  // Build the shared models.\n  const renames = new Map<string, string>();\n  for (const name of errorOnly) renames.set(name, canonical.get(keys.of(name))!);\n  const sharedModels: Model[] = [];\n  for (const [key, members] of orderedGroups) {\n    if (absorbed.has(key)) continue;\n    sharedModels.push(\n      buildSharedModel(\n        canonical.get(key)!,\n        members,\n        pinnedByKey.get(key)!,\n        enumValuesByField,\n        enumNamesByField,\n        renames,\n      ),\n    );\n  }\n\n  // Rewrite every error site, then fold the unions whose variants became one.\n  for (const slot of slots) renameTypeRefModels(slot.get()!, renames);\n  const simplified = new Map<TypeRef, TypeRef>();\n  for (const slot of slots) {\n    const type = slot.get()!;\n    let replacement = simplified.get(type);\n    if (replacement === undefined) {\n      replacement = simplifyType(type);\n      simplified.set(type, replacement);\n    }\n    if (replacement !== type) slot.set(replacement);\n  }\n\n  return {\n    models: [\n      ...input.models.filter((model) => !errorOnly.has(model.name)),\n      ...sharedModels.sort((a, b) => a.name.localeCompare(b.name)),\n    ],\n    frozen: new Set(),\n  };\n}\n\ntype OperationErrorSites = Pick<Service['operations'][number], 'errors' | 'rangeResponses'>;\n\n/** Every error site of `operations` (`ErrorSlot`), in document order. */\nfunction errorSlots(operations: readonly OperationErrorSites[]): ErrorSlot[] {\n  const slots: ErrorSlot[] = [];\n  const entrySlots = (entry: { type?: TypeRef; contents?: Array<{ type: TypeRef }> }): void => {\n    slots.push({\n      get: () => entry.type,\n      set: (type) => {\n        entry.type = type;\n      },\n    });\n    for (const content of entry.contents ?? []) {\n      slots.push({\n        get: () => content.type,\n        set: (type) => {\n          content.type = type;\n        },\n      });\n    }\n  };\n  for (const op of operations) {\n    for (const error of op.errors) entrySlots(error);\n    for (const range of op.rangeResponses ?? []) if (isErrorStatusRange(range.range)) entrySlots(range);\n  }\n  return slots;\n}\n\n/** Every model name reachable from `roots` through model fields and variants. */\nfunction closure(roots: readonly string[], byName: ReadonlyMap<string, Model>): Set<string> {\n  const reached = new Set<string>();\n  const stack = [...roots];\n  while (stack.length > 0) {\n    const name = stack.pop()!;\n    if (reached.has(name)) continue;\n    reached.add(name);\n    const model = byName.get(name);\n    if (!model) continue;\n    for (const ref of collectModelTypeRefs(model)) stack.push(...collectModelRefs(ref));\n  }\n  return reached;\n}\n\n/**\n * The structure of an error-only model, independent of its name, its\n * documentation, its `x-` extensions and the values its string fields are\n * pinned to. Memoized per model; a cycle among error bodies reads as the\n * name on the cycle.\n */\nclass ModelKeys {\n  private readonly keys = new Map<string, string>();\n  private readonly visiting = new Set<string>();\n\n  constructor(\n    private readonly errorOnly: ReadonlySet<string>,\n    private readonly byName: ReadonlyMap<string, Model>,\n  ) {}\n\n  of(name: string): string {\n    const cached = this.keys.get(name);\n    if (cached !== undefined) return cached;\n    if (this.visiting.has(name)) return `cycle:${name}`;\n    this.visiting.add(name);\n    const model = this.byName.get(name)!;\n    const fields = model.fields\n      .map((field) => `${field.name}${field.required ? '!' : '?'}${fieldFlags(field)}=${this.type(field.type, true)}`)\n      .sort()\n      .join('|');\n    const own = stableJson({\n      deprecated: model.deprecated,\n      constraints: model.constraints,\n      typeParams: model.typeParams,\n      compositionKind: model.compositionKind,\n      variants: model.variants?.map((variant) => this.type(variant, false)).sort(),\n      discriminator: model.discriminator && this.discriminator(model.discriminator),\n    });\n    const key = `${fields}#${own}`;\n    this.visiting.delete(name);\n    this.keys.set(name, key);\n    return key;\n  }\n\n  /**\n   * A type's structure. A field's own type (`direct`, through a nullable\n   * wrapper) reads every way the document pins or frees a string as one `S`,\n   * since `sharedFieldType` reads those values across the group; a string\n   * inside an array, union or map keeps its value in the key (`L\"a\"`,\n   * `E[\"a\",\"b\"]`), since nothing combines values there, so two bodies that\n   * list different codes in an array stay two models.\n   */\n  type(type: TypeRef, direct: boolean): string {\n    switch (type.kind) {\n      case 'literal':\n        return direct && typeof type.value === 'string' ? 'S' : `L${JSON.stringify(type.value)}`;\n      case 'enum':\n        if (isStringValuedInlineEnum(type)) return direct ? 'S' : `E${JSON.stringify([...type.values!].sort())}`;\n        return type.values ? `E${JSON.stringify(type.values)}` : `E:${type.name}`;\n      case 'primitive':\n        return direct && type.type === 'string' && !type.format ? 'S' : `P:${type.type}:${type.format ?? ''}`;\n      case 'model':\n        return this.errorOnly.has(type.name) ? `M{${this.of(type.name)}}` : `R:${type.name}`;\n      case 'array':\n        return `A[${this.type(type.items, false)}]`;\n      case 'nullable':\n        return `N(${this.type(type.inner, direct)})`;\n      case 'union': {\n        const variants = type.variants.map((variant) => this.type(variant, false)).sort();\n        const discriminator = type.discriminator ? this.discriminator(type.discriminator) : '';\n        return `U${type.compositionKind ?? ''}${discriminator}(${variants.join(',')})`;\n      }\n      case 'map':\n        return `Map(${type.keyType ? this.type(type.keyType, false) : ''};${this.type(type.valueType, false)})`;\n    }\n  }\n\n  /** A discriminator's property and every mapping entry, the target read as the variants are. */\n  private discriminator(discriminator: { property: string; mapping: Record<string, string> }): string {\n    const entries = Object.entries(discriminator.mapping)\n      .map(([value, target]) => `${value}=${this.errorOnly.has(target) ? `M{${this.of(target)}}` : `R:${target}`}`)\n      .sort();\n    return `@${discriminator.property}{${entries.join(',')}}`;\n  }\n}\n\n/** A field's flags, limits and domain name: everything but its name, type, documentation and extensions. */\nfunction fieldFlags(field: Field): string {\n  return stableJson({\n    domainName: field.domainName,\n    readOnly: field.readOnly,\n    writeOnly: field.writeOnly,\n    deprecated: field.deprecated,\n    default: field.default,\n    constraints: field.constraints,\n  });\n}\n\n/** For every string field of the members (by name), the values pinned and whether any member leaves it free. */\nfunction pinnedValues(members: readonly Model[]): Map<string, PinnedValues> {\n  const pinned = new Map<string, PinnedValues>();\n  for (const field of members[0].fields) {\n    if (!isStringLike(unwrapNullable(field.type))) continue;\n    const entry: PinnedValues = { values: new Set(), open: false };\n    for (const member of members) {\n      const sibling = member.fields.find((f) => f.name === field.name);\n      const inner = sibling ? unwrapNullable(sibling.type) : undefined;\n      if (inner?.kind === 'literal' && typeof inner.value === 'string') entry.values.add(inner.value);\n      else if (inner?.kind === 'enum' && isStringValuedInlineEnum(inner)) {\n        for (const value of inner.values!) entry.values.add(String(value));\n      } else entry.open = true;\n    }\n    pinned.set(field.name, entry);\n  }\n  return pinned;\n}\n\n/** The field set of the OAuth 2.0 error response. */\nconst OAUTH_ERROR_FIELDS = ['error', 'error_description'];\n\n/** The fields that carry an error code; a body pinned on one is named from the value alone. */\nconst ERROR_CODE_FIELDS = ['code', 'error'];\n\n/**\n * Whether `component` admits every value the group pins: a string field the\n * group pins is, on the component, a plain string, or — when no member leaves\n * it free — a literal or inline enum holding every pinned value. The key\n * reads every string as one, so this is what tells a component the bodies\n * can reference from one that would narrow their codes.\n */\nfunction componentAccepts(component: Model, pinned: ReadonlyMap<string, PinnedValues>): boolean {\n  for (const [name, { values, open }] of pinned) {\n    const field = component.fields.find((f) => f.name === name);\n    if (!field) return false;\n    const type = unwrapNullable(field.type);\n    if (type.kind === 'primitive' && type.type === 'string' && !type.format) continue;\n    if (open) return false;\n    if (type.kind === 'literal') {\n      if (values.size !== 1 || !values.has(String(type.value))) return false;\n      continue;\n    }\n    if (type.kind === 'enum' && type.values) {\n      const allowed = new Set(type.values.map((value) => String(value)));\n      if ([...values].some((value) => !allowed.has(value))) return false;\n      continue;\n    }\n    return false;\n  }\n  return true;\n}\n\n/** `{ code, message? }`: a model's field names, the optional ones marked. */\nfunction shapeOf(model: Model): string {\n  return `{ ${model.fields.map((field) => (field.required ? field.name : `${field.name}?`)).join(', ')} }`;\n}\n\n/** The one string field every member of a group pins to one value, when there is exactly one such field and the value can name a model. */\nfunction singlePinned(pinned: ReadonlyMap<string, PinnedValues>): { field: string; value: string } | undefined {\n  const single = [...pinned.entries()].filter(([, { values, open }]) => values.size === 1 && !open);\n  if (single.length !== 1) return undefined;\n  const [field, { values }] = single[0];\n  const value = [...values][0];\n  const word = toPascalCase(value);\n  // A value that is empty or starts with a digit (`4001`) names nothing.\n  if (word.length === 0 || /^\\d/.test(word)) return undefined;\n  return { field, value };\n}\n\n/**\n * The name a group takes: `ErrorBody` for `{ message }`, `OAuthErrorBody`\n * for `{ error, error_description }`, else the base plus `With` and a token\n * per further field (`fieldToken`). A group every member of which pins one\n * string field to one value is named from the value instead — followed by\n * the field's name unless it is `code` or `error` — plus `With` and the plain\n * names of any further fields.\n */\nfunction bodyName(\n  representative: Model,\n  pinned: ReadonlyMap<string, PinnedValues>,\n  errorOnly: ReadonlySet<string>,\n  byName: ReadonlyMap<string, Model>,\n): string {\n  const fields = [...representative.fields].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n  if (fields.length === 0) return `${ERROR_BODY_BASE}Empty`;\n  const names = new Set(fields.map((field) => field.name));\n  const oauth = OAUTH_ERROR_FIELDS.every((name) => names.has(name));\n  const base = oauth ? `OAuth${ERROR_BODY_BASE}` : ERROR_BODY_BASE;\n  const single = singlePinned(pinned);\n  const isProse = (field: Field): boolean =>\n    (field.name === 'message' || (oauth && field.name === 'error_description')) &&\n    isStringLike(unwrapNullable(field.type));\n  const core = new Set<string>([...(oauth ? ['error'] : []), ...(single ? [single.field] : [])]);\n  const extras = fields\n    .filter((field) => !core.has(field.name) && !isProse(field))\n    .map((field) => fieldToken(field.name, field.type, names, single === undefined, errorOnly, byName));\n  const suffix = extras.length === 0 ? '' : `With${extras.join('')}`;\n  if (single === undefined) return `${base}${suffix}`;\n  const field = ERROR_CODE_FIELDS.includes(single.field) ? '' : toPascalCase(single.field);\n  return `${toPascalCase(single.value)}${field}${base}${suffix}`;\n}\n\n/**\n * The token a field contributes to a body's name: its name in PascalCase;\n * `List` appended for an array of plain values; a union's variants joined\n * with `Or`; and, when `qualify` is set, a nested error body's own field\n * names (the ones the parent lacks) prefixed, so `errors` arrays of\n * different items read apart (`CodeFieldErrors`, `ConstraintsPropertyErrors`).\n */\nfunction fieldToken(\n  name: string,\n  type: TypeRef,\n  parentNames: ReadonlySet<string>,\n  qualify: boolean,\n  errorOnly: ReadonlySet<string>,\n  byName: ReadonlyMap<string, Model>,\n): string {\n  const word = toPascalCase(name);\n  const inner = unwrapNullable(type);\n  switch (inner.kind) {\n    case 'union': {\n      // Sorted, as the key sorts the variants: the name does not depend on\n      // which member of the group wrote the union first.\n      const tokens = inner.variants.map((variant) =>\n        fieldToken(name, variant, parentNames, qualify, errorOnly, byName),\n      );\n      return [...new Set(tokens)].sort().join('Or') || word;\n    }\n    case 'array': {\n      const items = unwrapNullable(inner.items);\n      if (items.kind === 'model' || items.kind === 'union') {\n        return fieldToken(name, items, parentNames, qualify, errorOnly, byName);\n      }\n      return `${word}List`;\n    }\n    case 'model': {\n      const nested = qualify && errorOnly.has(inner.name) ? byName.get(inner.name) : undefined;\n      const own = nested\n        ? nested.fields\n            .map((field) => field.name)\n            .filter((fieldName) => !parentNames.has(fieldName))\n            .sort()\n            .map((fieldName) => toPascalCase(fieldName))\n            .join('')\n        : '';\n      return `${own}${word}`;\n    }\n    default:\n      return word;\n  }\n}\n\n/**\n * The name of a nested error body reached through `field` of a body named\n * `parentName`: the parent's name plus the field, singular for an array\n * item, replacing the field where the parent's name already ends in it.\n */\nfunction nestedName(parentName: string, field: Field): string {\n  const word = toPascalCase(field.name);\n  const inArray = unwrapNullable(field.type).kind === 'array';\n  const item = inArray ? toPascalCase(singularize(field.name)) : word;\n  return inArray && word.length > 0 && parentName.endsWith(word)\n    ? `${parentName.slice(0, -word.length)}${item}`\n    : `${parentName}${item}`;\n}\n\n/**\n * One shared model for `members`, built on the first member's field order:\n * each field's type reads as the group reads it (`sharedFieldType`); its\n * description, example and extensions are kept when every member wrote the\n * same one, and the example only while the type is still the member's own.\n */\nfunction buildSharedModel(\n  name: string,\n  members: readonly Model[],\n  pinned: ReadonlyMap<string, PinnedValues>,\n  enumValuesByField: ReadonlyMap<string, ReadonlySet<string>>,\n  enumNamesByField: ReadonlyMap<string, string>,\n  renames: ReadonlyMap<string, string>,\n): Model {\n  const representative = members[0];\n  const fields: Field[] = representative.fields.map((field) => {\n    const siblings = members.map((member) => member.fields.find((f) => f.name === field.name)!);\n    const agree = <K extends keyof Field>(key: K): Field[K] | undefined =>\n      siblings.every((sibling) => stableJson(sibling[key]) === stableJson(field[key])) ? field[key] : undefined;\n    const { type, changed } = sharedFieldType(\n      field,\n      pinned.get(field.name),\n      enumValuesByField,\n      enumNamesByField,\n      renames,\n    );\n    const shared: Field = { name: field.name, type, required: field.required };\n    // Every member agrees on the domain name: it is part of the key.\n    if (field.domainName !== undefined) shared.domainName = field.domainName;\n    const description = agree('description');\n    if (description !== undefined) shared.description = description;\n    if (field.readOnly !== undefined) shared.readOnly = field.readOnly;\n    if (field.writeOnly !== undefined) shared.writeOnly = field.writeOnly;\n    if (field.deprecated !== undefined) shared.deprecated = field.deprecated;\n    if (field.default !== undefined) shared.default = field.default;\n    if (field.constraints !== undefined) shared.constraints = field.constraints;\n    const extensions = agree('extensions');\n    if (extensions !== undefined) shared.extensions = extensions;\n    if (!changed) {\n      const example = agree('example');\n      if (example !== undefined) shared.example = example;\n      const examples = agree('examples');\n      if (examples !== undefined) shared.examples = examples;\n      const externalDocs = agree('externalDocs');\n      if (externalDocs !== undefined) shared.externalDocs = externalDocs;\n    }\n    return shared;\n  });\n  const model: Model = { name, fields };\n  if (representative.deprecated !== undefined) model.deprecated = representative.deprecated;\n  if (representative.constraints !== undefined) model.constraints = representative.constraints;\n  if (representative.typeParams !== undefined) model.typeParams = representative.typeParams;\n  if (members.every((member) => stableJson(member.extensions) === stableJson(representative.extensions))) {\n    if (representative.extensions !== undefined) model.extensions = representative.extensions;\n  }\n  if (representative.variants) {\n    const union = simplifyType({\n      kind: 'union',\n      variants: representative.variants.map((variant) => rewritten(variant, renames)),\n      ...(representative.compositionKind && { compositionKind: representative.compositionKind }),\n    });\n    model.variants = union.kind === 'union' ? union.variants : [union];\n    if (representative.compositionKind !== undefined) model.compositionKind = representative.compositionKind;\n  }\n  if (representative.discriminator) {\n    const mapping: Record<string, string> = {};\n    for (const [value, target] of Object.entries(representative.discriminator.mapping)) {\n      mapping[value] = renames.get(target) ?? target;\n    }\n    model.discriminator = { property: representative.discriminator.property, mapping };\n  }\n  return model;\n}\n\n/**\n * The type a shared model gives a field. A string the group pins — a\n * `const`, an inline `enum`, beside a plain `string` — is read as a whole:\n * two or more distinct values make the enum shared by every error body\n * with a field of that name, `<ErrorBody><Field>`, holding every value any\n * body pins it to (a string when that name is taken); one value every\n * member pins stays that literal; one value beside free strings is a\n * string. Any other type is the representative's, its references to folded\n * models repointed.\n */\nfunction sharedFieldType(\n  field: Field,\n  pinned: PinnedValues | undefined,\n  enumValuesByField: ReadonlyMap<string, ReadonlySet<string>>,\n  enumNamesByField: ReadonlyMap<string, string>,\n  renames: ReadonlyMap<string, string>,\n): { type: TypeRef; changed: boolean } {\n  if (pinned) {\n    const nullable = field.type.kind === 'nullable';\n    let type: TypeRef;\n    const enumName = enumNamesByField.get(field.name);\n    if (pinned.values.size >= 2 && enumName !== undefined) {\n      const enumRef: EnumRef = {\n        kind: 'enum',\n        name: enumName,\n        values: [...(enumValuesByField.get(field.name) ?? pinned.values)].sort(),\n      };\n      type = enumRef;\n    } else if (pinned.values.size === 1 && !pinned.open) {\n      type = { kind: 'literal', value: [...pinned.values][0] };\n    } else {\n      type = { kind: 'primitive', type: 'string' };\n    }\n    const wrapped: TypeRef = nullable ? { kind: 'nullable', inner: type } : type;\n    return { type: wrapped, changed: stableJson(wrapped) !== stableJson(field.type) };\n  }\n  return { type: rewritten(field.type, renames), changed: false };\n}\n\n/** `type` with every reference to a folded model repointed, as a new tree. */\nfunction rewritten(type: TypeRef, renames: ReadonlyMap<string, string>): TypeRef {\n  const copy = structuredClone(type);\n  renameTypeRefModels(copy, renames);\n  return simplifyType(copy);\n}\n\n/**\n * A union whose variants fold onto fewer models, with the duplicates dropped\n * and a lone survivor standing in for the union; a nullable, array or map\n * simplified inside. Any other type is returned as it is.\n */\nfunction simplifyType(type: TypeRef): TypeRef {\n  switch (type.kind) {\n    case 'union': {\n      const seen = new Set<string>();\n      const variants: TypeRef[] = [];\n      for (const variant of type.variants) {\n        const simplifiedVariant = simplifyType(variant);\n        const key = stableJson(simplifiedVariant);\n        if (seen.has(key)) continue;\n        seen.add(key);\n        variants.push(simplifiedVariant);\n      }\n      if (variants.length === 1) return variants[0];\n      if (variants.length === type.variants.length && variants.every((variant, i) => variant === type.variants[i])) {\n        return type;\n      }\n      const union: UnionType = { ...type, variants };\n      return union;\n    }\n    case 'nullable': {\n      const inner = simplifyType(type.inner);\n      return inner === type.inner ? type : { kind: 'nullable', inner };\n    }\n    case 'array': {\n      const items = simplifyType(type.items);\n      return items === type.items ? type : { ...type, items };\n    }\n    case 'map': {\n      const valueType = simplifyType(type.valueType);\n      return valueType === type.valueType ? type : { ...type, valueType };\n    }\n    default:\n      return type;\n  }\n}\n\nfunction unwrapNullable(type: TypeRef): TypeRef {\n  return type.kind === 'nullable' ? unwrapNullable(type.inner) : type;\n}\n\n/** A plain string, a string literal, or an inline enum of strings: the shapes the pass reads as one. */\nfunction isStringLike(type: TypeRef): boolean {\n  if (type.kind === 'literal') return typeof type.value === 'string';\n  if (type.kind === 'enum') return isStringValuedInlineEnum(type);\n  return type.kind === 'primitive' && type.type === 'string' && !type.format;\n}\n\nfunction isStringValuedInlineEnum(type: EnumRef): boolean {\n  return type.values !== undefined && type.values.length > 0 && type.values.every((value) => typeof value === 'string');\n}\n\n/** JSON with object keys sorted at every level, `undefined` members dropped. */\nfunction stableJson(value: unknown): string {\n  return JSON.stringify(value, (_key, v) => {\n    if (v && typeof v === 'object' && !Array.isArray(v)) {\n      return Object.fromEntries(\n        Object.entries(v as Record<string, unknown>)\n          .filter(([, member]) => member !== undefined)\n          .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n      );\n    }\n    return v;\n  });\n}\n","import type { ApiSpec, AuthScheme } from '../ir/types.js';\nimport { defaultSdkBehavior } from '../ir/sdk-behavior.js';\nimport { SpecParseError } from '../errors.js';\nimport { loadAndBundleSpec } from './refs.js';\nimport {\n  extractSchemas,\n  extractInlineModelsFromSchemas,\n  clearSchemaNameTransform,\n  resolveSchemaName,\n} from './schemas.js';\nimport { attachSharedRefs, extractOperations } from './operations.js';\nimport type { FieldInlineModelGroup } from './inline-models.js';\nimport { collectExistingEnumNames, collectExistingNames, extractWebhooks } from './webhooks.js';\nimport { siblingDocsMode } from './reference-objects.js';\nimport {\n  mergeInlineResponseModels,\n  collapseJsonSuffixModels,\n  mergeFieldInlineModels,\n  fieldInlineModelBundles,\n  refreshFieldInlineModelBundles,\n  reservedNamesByKind,\n  reservedTypeNames,\n  settleFieldInlineModels,\n  type InlineModelNaming,\n} from './normalize-inline-models.js';\nimport {\n  collectInlineEnumsFromModels,\n  collectInlineEnumsFromOperations,\n  collectInlineEnumsFromWebhooks,\n} from './collect-inline-enums.js';\nimport { assignParameterGroupWrapperNames } from './parameter-group-names.js';\nimport { validateModelRefs } from './normalize-model-refs.js';\nimport { collapseErrorBodies } from './collapse-error-bodies.js';\nimport { extractSecurityRequirements, type RawSecurityRequirements } from './security.js';\nimport { extractServers, type RawServerObject } from './servers.js';\nimport { externalDocsEntry, type RawExternalDocs } from './external-docs.js';\nimport type { SchemaNameTransform } from './schemas.js';\nimport type { OperationHint } from '../ir/operation-hints.js';\n\n/**\n * A bundled OpenAPI document, post-`$ref` resolution but pre-IR extraction.\n *\n * This is the shape the spec author wrote, with external refs inlined and\n * internal refs left intact. It is intentionally loose (`Record<string,\n * unknown>`) so `transformSpec` can reach arbitrary spec extensions without\n * fighting types — narrow with `as` at use sites.\n */\nexport type OpenApiDocument = Record<string, unknown>;\n\nexport interface ParseOptions {\n  operationIdTransform?: (id: string) => string;\n  /**\n   * Custom transform for schema (model/enum) names. Receives the cleaned\n   * PascalCase name and, for component schemas, the original name as spelled\n   * in the document. Returning `originalName` opts out of normalization.\n   * See `SchemaExtractionOptions.schemaNameTransform`.\n   */\n  schemaNameTransform?: SchemaNameTransform;\n  /**\n   * Domain-facing field-name overrides, keyed by IR model name then wire field\n   * name: `{ Connection: { connection_type: 'type' } }`. Sets `Field.domainName`\n   * so emitters expose the field under the friendlier name while keeping the\n   * wire key. Language-agnostic — honored by any emitter that reads `domainName`.\n   */\n  fieldHints?: Record<string, Record<string, string>>;\n  /**\n   * Per-operation overrides keyed by \"METHOD /path\" — the same map\n   * `resolveOperations` reads. The parser applies only each hint's\n   * `pagination`, which wins over the operation's `x-pagination` extension\n   * and over name-based detection (see `PaginationHint`).\n   */\n  operationHints?: Record<string, OperationHint>;\n  /**\n   * Fold the models materialized for inline error bodies onto shared models\n   * named by shape (`ErrorBody`, `ErrorBodyWithCode`, the enum `ErrorBodyCode`;\n   * see `collapseErrorBodies`). On by default; `false` keeps one model per\n   * operation and status code (`<Op>Error<code>`).\n   */\n  collapseErrorBodies?: boolean;\n  /**\n   * Pre-IR overlay applied to the bundled OpenAPI document before any IR\n   * extraction runs. Use this when the upstream spec can't be changed but you\n   * need to patch around a spec quirk that would otherwise emit a breaking SDK\n   * change — e.g. rewriting a path's response `$ref` back to its prior schema,\n   * merging the new fields onto the prior schema, and dropping the fork.\n   *\n   * The function may mutate the document in place and return it, or return a\n   * new object; the returned value is what the rest of oagen sees.\n   *\n   * Runs once, after `$ref` bundling and before schema/operation extraction.\n   * If you need to inspect the resulting IR instead, post-process the\n   * `ApiSpec` returned by `parseSpec`.\n   */\n  transformSpec?: (spec: OpenApiDocument) => OpenApiDocument;\n}\n\nexport async function parseSpec(specPath: string, options?: ParseOptions): Promise<ApiSpec> {\n  const { parsed } = await loadAndBundleSpec(specPath);\n  const transformed = options?.transformSpec ? options.transformSpec(parsed) : parsed;\n\n  const spec = transformed as {\n    openapi?: string;\n    info?: { title?: string; version?: string; description?: string };\n    servers?: RawServerObject[];\n    security?: RawSecurityRequirements;\n    tags?: Array<{ name?: string; description?: string; externalDocs?: RawExternalDocs }>;\n    externalDocs?: RawExternalDocs;\n    paths?: Record<string, unknown>;\n    webhooks?: unknown;\n    'x-webhooks'?: unknown;\n    components?: {\n      schemas?: Record<string, unknown>;\n      parameters?: Record<string, unknown>;\n      requestBodies?: Record<string, unknown>;\n      responses?: Record<string, unknown>;\n      examples?: Record<string, unknown>;\n      headers?: Record<string, unknown>;\n      pathItems?: Record<string, unknown>;\n      securitySchemes?: Record<string, SecuritySchemeObject>;\n    };\n  };\n\n  // Validate OpenAPI version\n  const version = spec.openapi ?? '';\n  if (!version.startsWith('3.')) {\n    throw new SpecParseError(\n      `Unsupported OpenAPI version: ${version}. oagen requires OpenAPI 3.x`,\n      `Update the spec to OpenAPI 3.0 or 3.1. If you are using Swagger 2.x, convert it first with \\`npx swagger2openapi ${specPath}\\`.`,\n    );\n  }\n\n  // The whole document goes along so the rules that read every inline schema\n  // of a root at once see the operations' and webhooks' schemas too, not\n  // only the components' (`SchemaExtractionOptions.document`).\n  const { models, enums } = extractSchemas(\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    { schemaNameTransform: options?.schemaNameTransform, document: transformed },\n  );\n\n  // Before the operations: an operation carries its own `servers` only when\n  // they differ from the document's, so the document's list is needed first.\n  const { servers, baseUrl } = extractServers(spec.servers);\n\n  // Extract inline models from model field definitions (objects/arrays with properties).\n  // schemaNameTransform is kept active so inline child names use the\n  // transformed parent name (e.g. AuditLogSchemaJson→AuditLogSchema yields\n  // AuditLogSchemaTarget, not AuditLogSchemaJsonTarget). Read before the\n  // operations and the webhooks so the names those mint — header and\n  // fallback models, webhook payloads — are reserved against these too: a\n  // map's values or a nested object a component field mints (`ReportDetail`)\n  // is not among `models`, and a titled fallback variant would otherwise take\n  // its name and the field merge below drop the component's definition.\n  // Each field's site is recorded too, so a merge pass that must rename one\n  // of these models can repoint exactly the references that mint it.\n  const fieldInlineModelGroups: FieldInlineModelGroup[] = [];\n  const extractedFieldModels = extractInlineModelsFromSchemas(\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    fieldInlineModelGroups,\n  );\n  // The components' own field models are settled against the components\n  // right here, before any operation or webhook is read\n  // (`settleFieldInlineModels`): a field object named like a component that\n  // does not admit it takes its qualified name now (`PetOwner2`), and one\n  // the component admits is dropped for it, so every later reader — the\n  // operations' bodies, the shape registry, the webhooks, the merges below —\n  // sees each component referencing its children by their final names, and\n  // no parent is ever compared with a component on an unsettled child. The\n  // names are minted against everything decided so far; a reference an\n  // `allOf` merge copies from such a field later is created under the\n  // settled name (`recordInheritedModelRefs`). A field object named like\n  // one of the document's enums (`enumNames`: the component enums and the\n  // enums the component pass lifted) takes its qualified name here too; one\n  // named like an enum an operation or webhook carries, which is not known\n  // yet, takes it when the merges below settle the fields again against\n  // every enum name in play.\n  const enumNames: ReadonlySet<string> = new Set(enums.map((e) => e.name));\n  // The names every merge pass mints, shared across the passes so a later\n  // one can tell a parent whose child an earlier pass renamed\n  // (`InlineModelNaming.minted`). Each field's site already holds the object\n  // the schema pass lifted from the field's own schema\n  // (`fieldInlineModelBundles`, `liftedFieldModelsOf`), so a copy dropped\n  // here for it needs no record.\n  const mintedNames = new Set<string>();\n  // The field sites, kept for the merges below (`refreshFieldInlineModelBundles`):\n  // what a fold carries onto a site here must still be there when a later\n  // pass renames the model it was carried onto.\n  const fieldInlineModelBundlesBySite = fieldInlineModelBundles(fieldInlineModelGroups, models);\n  const fieldInlineModels = settleFieldInlineModels(models, extractedFieldModels, {\n    bundles: fieldInlineModelBundlesBySite,\n    reserved: reservedTypeNames(models, enums, [], extractedFieldModels, []),\n    enums: enumNames,\n    minted: mintedNames,\n  });\n\n  const { services, inlineModels, inlineModelBundles, componentSites } = extractOperations(\n    spec.paths as Record<string, Record<string, unknown>> | undefined,\n    options?.operationIdTransform,\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.parameters as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.requestBodies as Record<string, Record<string, unknown>> | undefined,\n    models,\n    spec.tags,\n    spec.components?.examples as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.headers as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.responses as Record<string, Record<string, unknown>> | undefined,\n    fieldInlineModels,\n    servers,\n    version,\n    options?.operationHints,\n    // The component enums, so no model the operations pass mints — a header,\n    // parameter, fallback, error or secondary body's, an array body's items —\n    // takes one of their names.\n    enums,\n    // A `paths` entry may be a `$ref` into this map (OpenAPI 3.1); the\n    // webhooks below resolve theirs against the same one.\n    spec.components?.pathItems as Record<string, Record<string, unknown>> | undefined,\n  );\n\n  // Webhooks are read while the schema-name transform is still active, like\n  // operations, so a payload's `$ref`s resolve to the same names as a field's.\n  // Their models are named last, against every model and enum decided so far —\n  // components, operations, and the components' own inline field models — so\n  // a webhook never takes a name another pass has already minted.\n  const {\n    webhooks,\n    inlineModels: webhookInlineModels,\n    inlineModelBundles: webhookInlineModelBundles,\n  } = extractWebhooks(\n    spec.webhooks,\n    {\n      schemas: spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n      parameters: spec.components?.parameters as Record<string, Record<string, unknown>> | undefined,\n      requestBodies: spec.components?.requestBodies as Record<string, Record<string, unknown>> | undefined,\n      responses: spec.components?.responses as Record<string, Record<string, unknown>> | undefined,\n      examples: spec.components?.examples as Record<string, Record<string, unknown>> | undefined,\n      pathItems: spec.components?.pathItems as Record<string, Record<string, unknown>> | undefined,\n    },\n    collectExistingNames([...models, ...inlineModels, ...fieldInlineModels], services, enums),\n    collectExistingEnumNames([...models, ...inlineModels, ...fieldInlineModels], services, enums),\n    // Text beside a `$ref` is read by the document's version, as for operations.\n    siblingDocsMode(version),\n  );\n  warnOnLegacyWebhooks(spec['x-webhooks']);\n\n  // Resolved while the transform is still active so the names match the\n  // models'; lets the merge tell a clash with a component schema from one\n  // between two inline models.\n  const componentNames = new Set(\n    Object.keys(spec.components?.schemas ?? {}).map((schemaName) => resolveSchemaName(schemaName)),\n  );\n  clearSchemaNameTransform();\n\n  // Every name in play — component models and enums, every inline model of\n  // every pass, and every inline enum the collectors below will lift — so a\n  // copy a merge pass must rename (a response named like a component that\n  // does not admit it, a deprecated response named like a live one) takes a\n  // name nothing else has or will have, in either pass; and the enum names\n  // among them, which no inline model keeps: a `getPet` body beside a\n  // component enum `GetPetResponse` steps to `GetPetResponse2`, and so does\n  // a `createPet` body beside a `request` query enum of its service named\n  // `CreatePetRequest`, as a `request` parameter object beside that enum\n  // steps in the shape registry (`reserveEnumNames`) — the model steps\n  // wherever an enum of its name exists, so the IR never declares a model\n  // and an enum under one name. An enum the collectors lift after a model\n  // of its name that no pass could rename (a component model) steps itself\n  // (`collectDistinctEnums`). Every site is here: the operations', the\n  // webhooks', and the component fields' — read again, with the references\n  // the operations' and webhooks' `allOf` merges have copied from component\n  // fields since the fields were settled.\n  const reserved = reservedNamesByKind(\n    models,\n    enums,\n    [...inlineModels, ...webhookInlineModels],\n    fieldInlineModels,\n    services,\n    webhooks,\n  );\n  const naming: InlineModelNaming = {\n    bundles: [\n      ...inlineModelBundles,\n      ...webhookInlineModelBundles,\n      // The field sites from the settle, brought up to date: each holds the\n      // object the schema pass lifted from the field's own schema, which the\n      // extracted copy folded onto at the settle, and whatever a fold carried\n      // onto it there, so a rename here reaches all of it; the references a\n      // header or fallback body wrote by sharing that object join the site\n      // below (`attachSharedRefs`) and follow the rename.\n      ...refreshFieldInlineModelBundles(fieldInlineModelBundlesBySite, fieldInlineModelGroups, fieldInlineModels),\n    ],\n    reserved: reserved.all,\n    enums: reserved.enums,\n    minted: mintedNames,\n  };\n  // The components' field models, settled above, own their names here as\n  // the components do (`declared`), so a nested object of a response named\n  // like one is decided against it before its parent is compared — never\n  // passed for it by name under a parent the lifted model admits.\n  const responseNormalizedModels = mergeInlineResponseModels(\n    models,\n    [...inlineModels, ...webhookInlineModels],\n    naming,\n    fieldInlineModels,\n  );\n  // An operation's array items that share a component field's model\n  // (`typeInlineItems`) join that field's site, so a rename of the field's\n  // model reaches the array too (`attachSharedRefs`).\n  attachSharedRefs(naming.bundles, componentNames);\n  const fieldMergedModels = mergeFieldInlineModels(responseNormalizedModels, fieldInlineModels, componentNames, naming);\n  const finalModels = collapseJsonSuffixModels(fieldMergedModels, services, webhooks, enums, componentNames);\n  applyFieldHints(finalModels, options?.fieldHints);\n  // The inline error bodies, one model per operation and status code until here,\n  // fold onto shared models named by shape (`ErrorBody`, `ErrorBodyWithCode`),\n  // their pinned `code`s gathered into one enum the collectors below lift.\n  const collapsedModels =\n    options?.collapseErrorBodies === false\n      ? finalModels\n      : collapseErrorBodies({ services, webhooks, models: finalModels }, { componentNames, componentSites, enums });\n  // A hint keyed by a shared model's name (`ErrorBodyWithCode`) applies here;\n  // one keyed by a folded model's name was applied above and rode along.\n  applyFieldHints(collapsedModels, options?.fieldHints);\n  // Each collector steps a renamed enum around every model name as well as\n  // every enum's, so the merge passes above (which mint against every enum\n  // name an `EnumRef` carries) and the collectors never meet on one name.\n  collectInlineEnumsFromModels(collapsedModels, enums);\n  collectInlineEnumsFromOperations(services, enums, componentSites, collapsedModels, componentNames);\n  collectInlineEnumsFromWebhooks(webhooks, enums, collapsedModels);\n\n  const auth = extractAuthSchemes(spec.components?.securitySchemes);\n\n  const result: ApiSpec = {\n    name: spec.info?.title ?? 'Unknown API',\n    version: spec.info?.version ?? '0.0.0',\n    description: spec.info?.description,\n    // The document's own link; the key stays absent when it declares none.\n    ...externalDocsEntry(spec.externalDocs),\n    baseUrl,\n    servers,\n    services,\n    // Omitted, not an empty list, for a document without webhooks so its IR\n    // keeps the shape it had before the key existed.\n    ...(webhooks.length > 0 ? { webhooks } : {}),\n    models: collapsedModels,\n    enums,\n    auth,\n    security: extractSecurityRequirements(spec.security, 'the document'),\n    sdk: defaultSdkBehavior(),\n  };\n\n  // Needs the finished models and enums: divergence is decided on member\n  // shape, so this can only run once every referenced type is resolvable.\n  assignParameterGroupWrapperNames(result);\n\n  validateModelRefs(result);\n\n  return result;\n}\n/**\n * Apply `fieldHints` onto the built models, setting `Field.domainName` for each\n * matching (model name, wire field name) pair. Serialization still uses\n * `Field.name`; only the domain-facing identifier changes.\n */\nfunction applyFieldHints(\n  models: import('../ir/types.js').Model[],\n  fieldHints: Record<string, Record<string, string>> | undefined,\n): void {\n  if (!fieldHints) return;\n  for (const model of models) {\n    const hints = fieldHints[model.name];\n    if (!hints) continue;\n    for (const field of model.fields) {\n      const domainName = hints[field.name];\n      if (domainName) field.domainName = domainName;\n    }\n  }\n}\n\n/**\n * `x-webhooks` is the extension some OpenAPI 3.0 documents use for what 3.1\n * standardized as the top-level `webhooks` map. The parser deliberately reads\n * the standard key only: an extension has no agreed shape to parse, and\n * reading it silently would make the IR depend on a convention the document\n * never declared. A document that carries one is told so, once, so the\n * omission is a visible choice rather than a quiet loss. An operation's\n * `callbacks`, which are not read either, are reported per operation by\n * `warnOnIgnoredCallbacks` at the sites that read Operation Objects.\n */\nfunction warnOnLegacyWebhooks(legacy: unknown): void {\n  if (typeof legacy !== 'object' || legacy === null) return;\n  console.warn(\n    '[oagen] Warning: `x-webhooks` is not read. Declare the webhooks under the top-level `webhooks` map (OpenAPI 3.1) to have them parsed.',\n  );\n}\n\n/** A `components.securitySchemes` entry as it appears in the OpenAPI document. */\ninterface SecuritySchemeObject {\n  type: string;\n  description?: string;\n  scheme?: string;\n  in?: string;\n  name?: string;\n  flows?: Record<string, unknown>;\n}\n\n/**\n * Extract authentication schemes from OpenAPI securitySchemes.\n *\n * Document order is preserved. Each entry carries its `securitySchemes` key as\n * `schemeName` so emitters can join the requirements under `ApiSpec.security`\n * and `Operation.security` back to it.\n * Schemes the IR cannot represent are omitted with a warning rather than silently.\n */\nfunction extractAuthSchemes(securitySchemes?: Record<string, SecuritySchemeObject>): AuthScheme[] | undefined {\n  if (!securitySchemes) return undefined;\n  const schemes: AuthScheme[] = [];\n  for (const [schemeName, scheme] of Object.entries(securitySchemes)) {\n    // Omit `description` entirely (rather than setting it to undefined) when the\n    // document does not declare one. An explicit empty string is a declared value\n    // and is kept, so consumers can tell \"empty\" from \"missing\".\n    const common = scheme.description !== undefined ? { schemeName, description: scheme.description } : { schemeName };\n    // HTTP authentication scheme names are case-insensitive (RFC 9110 §11.1).\n    const httpScheme = scheme.type === 'http' ? scheme.scheme?.toLowerCase() : undefined;\n    if (httpScheme === 'bearer') {\n      schemes.push({ kind: 'bearer', ...common });\n    } else if (httpScheme === 'basic') {\n      schemes.push({ kind: 'basic', ...common });\n    } else if (scheme.type === 'apiKey' && scheme.in && scheme.name) {\n      schemes.push({ kind: 'apiKey', ...common, in: scheme.in as 'header' | 'query' | 'cookie', name: scheme.name });\n    } else if (scheme.type === 'oauth2' && scheme.flows) {\n      schemes.push({ kind: 'oauth2', ...common, flows: scheme.flows });\n    } else {\n      // Other http schemes (digest, ...), openIdConnect, mutualTLS, and malformed\n      // entries have no IR representation; say so instead of dropping them silently.\n      const detail = scheme.type === 'http' ? `type: http, scheme: ${scheme.scheme}` : `type: ${scheme.type}`;\n      console.warn(`[oagen] Warning: Unsupported security scheme \"${schemeName}\" (${detail}) omitted from spec.auth`);\n    }\n  }\n  return schemes.length > 0 ? schemes : undefined;\n}\n","import type { Operation, TypeRef } from '../ir/types.js';\nimport { assertNever } from '../ir/types.js';\n\nexport interface OperationPlan {\n  operation: Operation;\n  isDelete: boolean;\n  hasBody: boolean;\n  isIdempotentPost: boolean;\n  pathParamsInOptions: boolean;\n  isPaginated: boolean;\n  responseModelName: string | null;\n  /** For paginated operations, the model name of individual list items\n   *  (unwrapped from the list wrapper). Null for non-paginated. */\n  paginatedItemModelName: string | null;\n  isModelResponse: boolean;\n  /** True when the response is an unpaginated `type: array` of models.\n   *  Emitters should use this to return `Model[]` (or the language's list\n   *  equivalent) and map the deserializer over each element. */\n  isArrayResponse: boolean;\n  hasQueryParams: boolean;\n  isAsync: boolean;\n}\n\nexport function planOperation(op: Operation): OperationPlan {\n  const isDelete = op.httpMethod === 'delete';\n  const hasBody = !!op.requestBody;\n  const isIdempotentPost = op.injectIdempotencyKey && op.httpMethod === 'post';\n  const hasQueryParams = op.queryParams.length > 0;\n  const pathParamsInOptions = op.pathParams.length > 1 || (op.pathParams.length > 0 && (hasBody || hasQueryParams));\n  const isPaginated = op.pagination !== undefined;\n  const responseModelName = resolveResponseModelName(op);\n  const paginatedItemModelName =\n    isPaginated && op.pagination?.itemType.kind === 'model' ? op.pagination.itemType.name : null;\n  const isModelResponse = responseModelName !== null;\n  // Unpaginated `type: array` of models — needs `Model[]` return + elementwise\n  // deserialization.  Paginated operations use the pagination wrapper instead.\n  const isArrayResponse = !isPaginated && op.response.kind === 'array' && op.response.items.kind === 'model';\n  const isAsync = op.async ?? true;\n\n  return {\n    operation: op,\n    isDelete,\n    hasBody,\n    isIdempotentPost,\n    pathParamsInOptions,\n    isPaginated,\n    responseModelName,\n    paginatedItemModelName,\n    isModelResponse,\n    isArrayResponse,\n    hasQueryParams,\n    isAsync,\n  };\n}\n\nexport function resolveResponseModelName(op: Operation): string | null {\n  if (op.httpMethod === 'delete') return null;\n  return extractModelName(op.response);\n}\n\nfunction extractModelName(ref: TypeRef): string | null {\n  switch (ref.kind) {\n    case 'model':\n      return ref.name;\n    case 'array':\n      return ref.items.kind === 'model' ? ref.items.name : null;\n    case 'nullable':\n      return extractModelName(ref.inner);\n    case 'union': {\n      const firstModel = ref.variants.find((v) => v.kind === 'model');\n      return firstModel && firstModel.kind === 'model' ? firstModel.name : null;\n    }\n    case 'map':\n    case 'enum':\n    case 'primitive':\n    case 'literal':\n      return null;\n    default:\n      return assertNever(ref);\n  }\n}\n","/**\n * Escape a string for safe interpolation inside a JS/TS block comment.\n *\n * Free-text spec fields (schema/field/operation descriptions) are\n * attacker-influenceable data. A `*` followed by `/` inside such text would\n * terminate the surrounding `/* ... *\\/` comment and turn the remainder of the\n * string into live source in the generated output. Neutralizing every comment\n * terminator keeps the text inert inside the comment.\n *\n * This is specific to languages whose block comments end at `*\\/` (JS, TS,\n * Java, C#, Go, ...). Emitters for languages with other comment syntax (Python\n * `\"\"\"`, Ruby `=begin`/`#`, ...) must apply language-appropriate escaping\n * instead of, or in addition to, this helper.\n */\nexport function escapeBlockComment(text: string): string {\n  return text.replace(/\\*\\//g, '*\\\\/');\n}\n\n/**\n * Sanitize a string for safe interpolation into a JS/TS identifier position\n * (class name, variable, property, ...).\n *\n * Free-text spec fields flow into identifiers too — notably `info.title`, which\n * becomes the SDK namespace (and thus the client class name) when no explicit\n * `--namespace` is given. Interpolating that raw value into an identifier lets a\n * crafted title (e.g. `X {}; run(); class Y`) break out of the declaration and\n * emit arbitrary top-level source. Replacing every character that is not valid\n * in an identifier keeps the value inert.\n *\n * Already-valid identifiers pass through unchanged (`WorkOS` stays `WorkOS`), so\n * this does not disturb legitimate output. A leading digit is prefixed with `_`\n * so the result is always a usable identifier.\n */\nexport function sanitizeIdentifier(text: string): string {\n  const cleaned = text.replace(/[^A-Za-z0-9_$]/g, '_');\n  return /^[0-9]/.test(cleaned) ? `_${cleaned}` : cleaned;\n}\n","import type { ApiSpec, ArrayType, Constraints, Enum, Field, MapType, Model, Parameter, TypeRef } from '../ir/types.js';\n\n/**\n * Builds illustrative example values for IR types. Used by snippet emitters\n * to produce realistic argument values in call-site samples.\n *\n * Values prefer, in order:\n *   1. An explicit `example` carried on the field/param.\n *   2. The `default` from the schema.\n *   3. The first enum value, when the type is an enum.\n *   4. A type-driven value (e.g. `\"string_example\"`, `1`, `true`), generated\n *      inside the field's/param's `constraints` when it carries any.\n *\n * A document-given `example` or `default` is returned verbatim, never\n * adjusted, even when it violates a limit the same document declares: the\n * author's value is the better illustration, and a snippet is not a\n * validator. Only generated values are shaped by `constraints`:\n *\n *   - Numbers are chosen to satisfy every declared bound and `multipleOf`:\n *     with only a lower bound, the smallest value at or just past it (rounded\n *     up to the next multiple); with only an upper bound, the largest value\n *     at or just below it (rounded down); with both, the smallest integer\n *     inside for `integer` and the midpoint for `number`, snapped to a\n *     multiple inside the range; with none, `1` (or the first multiple).\n *     Only when no value can satisfy the limits together (contradictory\n *     bounds, or no multiple between them) is the lower bound returned as\n *     is.\n *   - Plain strings are padded (by repeating the sample) to `minLength` and\n *     truncated to `maxLength`; format-driven values (`date-time`, `email`,\n *     `uuid`, ...) are never touched. A `pattern` is not synthesized: the\n *     sample is kept even when it does not match, since generating a string\n *     from an arbitrary regex is out of scope.\n *   - Arrays emit `max(1, minItems)` items capped at `maxItems` (an explicit\n *     `maxItems: 0` gives `[]`). Under `uniqueItems`, generated primitives\n *     vary by index (strings get the index appended, numbers get it added,\n *     booleans alternate — so a unique boolean array holds at most two\n *     items); enum, literal and model items are not varied.\n *   - Maps emit `max(1, minProperties)` entries capped at `maxProperties`:\n *     one entry keeps the `key` name, more are `key1`, `key2`, ...\n *   - Model-level `minProperties` / `maxProperties` are ignored: every\n *     non-deprecated, non-readOnly field is emitted anyway.\n *\n * Snippets are illustrative, so generation has a size budget: at most\n * {@link MAX_GENERATED_LENGTH} characters per string and\n * {@link MAX_GENERATED_ITEMS} items per array or entries per map. A\n * `minLength`, `minItems` or `minProperties` above the budget yields the\n * capped size — a readable sample rather than a conforming one.\n *\n * Limits nested inside array items or map values are not carried by the\n * IR, so items and values are generated unconstrained.\n *\n * Recursion through models/arrays/maps is depth-limited; cyclic models\n * collapse to a placeholder object rather than blowing the stack.\n */\nexport interface ExampleBuilder {\n  /**\n   * Build an example value for a single type reference (no field metadata),\n   * generated inside `constraints` when given.\n   */\n  forType(type: TypeRef, constraints?: Constraints): unknown;\n  /** Build an example value for a field, honoring its `example`/`default` and `constraints`. */\n  forField(field: Field): unknown;\n  /** Build an example value for a parameter, honoring its `example`/`default` and `constraints`. */\n  forParameter(param: Parameter): unknown;\n  /** Build an example object from a model, keyed by field wire name. */\n  forModel(model: Model | string): Record<string, unknown>;\n}\n\nconst MAX_DEPTH = 6;\n/** Longest generated string; a larger `minLength` is capped here. */\nexport const MAX_GENERATED_LENGTH = 64;\n/** Most generated array items or map entries; a larger `minItems` / `minProperties` is capped here. */\nexport const MAX_GENERATED_ITEMS = 8;\n\nexport function createExampleBuilder(spec: ApiSpec): ExampleBuilder {\n  const modelsByName = new Map<string, Model>();\n  for (const m of spec.models) modelsByName.set(m.name, m);\n  const enumsByName = new Map<string, Enum>();\n  for (const e of spec.enums) enumsByName.set(e.name, e);\n\n  /**\n   * `seed` distinguishes sibling items of a `uniqueItems` array: it is\n   * appended to generated strings, added to generated numbers and alternates\n   * generated booleans. `0` leaves the value as is.\n   */\n  function buildForType(type: TypeRef, depth: number, constraints?: Constraints, seed = 0): unknown {\n    if (depth > MAX_DEPTH) return null;\n\n    switch (type.kind) {\n      case 'primitive':\n        return primitiveExample(type.type, type.format, constraints, seed);\n      case 'literal':\n        return type.value;\n      case 'enum': {\n        if (type.values && type.values.length > 0) return type.values[0];\n        const e = enumsByName.get(type.name);\n        return e?.values[0]?.value ?? null;\n      }\n      case 'array':\n        return arrayExample(type, depth, constraints);\n      case 'nullable':\n        return buildForType(type.inner, depth, constraints, seed);\n      case 'union': {\n        const first = type.variants[0];\n        return first ? buildForType(first, depth, constraints, seed) : null;\n      }\n      case 'map':\n        return mapExample(type, depth, constraints);\n      case 'model':\n        return buildForModel(type.name, depth + 1);\n      default:\n        return null;\n    }\n  }\n\n  function arrayExample(type: ArrayType, depth: number, constraints?: Constraints): unknown[] {\n    let count = countWithin(constraints?.minItems, constraints?.maxItems);\n    const vary = constraints?.uniqueItems === true && count > 1;\n    // Booleans only have two distinct values, so a unique boolean array\n    // cannot hold more than two items.\n    if (vary && isBooleanType(type.items)) count = Math.min(count, 2);\n    const items: unknown[] = [];\n    for (let i = 0; i < count; i++) {\n      items.push(buildForType(type.items, depth + 1, undefined, vary ? i : 0));\n    }\n    return items;\n  }\n\n  function mapExample(type: MapType, depth: number, constraints?: Constraints): Record<string, unknown> {\n    const count = countWithin(constraints?.minProperties, constraints?.maxProperties);\n    const result: Record<string, unknown> = {};\n    for (let i = 0; i < count; i++) {\n      const key = count === 1 ? 'key' : `key${i + 1}`;\n      result[key] = buildForType(type.valueType, depth + 1);\n    }\n    return result;\n  }\n\n  function buildForModel(nameOrModel: string | Model, depth: number): Record<string, unknown> {\n    if (depth > MAX_DEPTH) return {};\n    const model = typeof nameOrModel === 'string' ? modelsByName.get(nameOrModel) : nameOrModel;\n    if (!model) return {};\n\n    // Model-level minProperties / maxProperties are not consulted: every\n    // non-deprecated, non-readOnly field is emitted regardless.\n    const result: Record<string, unknown> = {};\n    for (const field of model.fields) {\n      if (field.deprecated || field.readOnly) continue;\n      result[field.name] = buildForField(field, depth);\n    }\n    return result;\n  }\n\n  function buildForField(field: Field, depth: number): unknown {\n    if (field.example !== undefined) return field.example;\n    if (field.default !== undefined) return field.default;\n    return buildForType(field.type, depth, field.constraints);\n  }\n\n  function buildForParameter(param: Parameter): unknown {\n    if (param.example !== undefined) return param.example;\n    if (param.default !== undefined) return param.default;\n    return buildForType(param.type, 0, param.constraints);\n  }\n\n  return {\n    forType: (type, constraints) => buildForType(type, 0, constraints),\n    forField: (field) => buildForField(field, 0),\n    forParameter: (param) => buildForParameter(param),\n    forModel: (model) => buildForModel(model, 0),\n  };\n}\n\n/** True for a boolean primitive, looking through `nullable`. */\nfunction isBooleanType(type: TypeRef): boolean {\n  if (type.kind === 'nullable') return isBooleanType(type.inner);\n  return type.kind === 'primitive' && type.type === 'boolean';\n}\n\n/**\n * `max(1, min)` capped at the size budget and then at `max`; an explicit\n * `max: 0` yields `0`.\n */\nfunction countWithin(min: number | undefined, max: number | undefined): number {\n  let count = Math.min(Math.max(1, min ?? 0), MAX_GENERATED_ITEMS);\n  if (max !== undefined) count = Math.min(count, max);\n  return Math.max(0, Math.floor(count));\n}\n\nfunction primitiveExample(type: string, format: string | undefined, constraints?: Constraints, seed = 0): unknown {\n  switch (type) {\n    case 'string':\n      return stringExample(format, constraints, seed);\n    case 'integer':\n      return numberExample(true, constraints) + seed;\n    case 'number':\n      return numberExample(false, constraints) + seed;\n    case 'boolean':\n      return seed % 2 === 0;\n    case 'unknown':\n    default:\n      return null;\n  }\n}\n\nconst STRING_SAMPLE = 'string_example';\n\n/**\n * Format-driven samples are returned untouched. The plain sample is padded\n * to `minLength` (within the size budget) and truncated to `maxLength`;\n * when both conflict, `maxLength` wins so the result at least fits. A\n * `pattern` is deliberately not honored.\n */\nfunction stringExample(format: string | undefined, constraints?: Constraints, seed = 0): string {\n  if (format === 'date-time') return '2026-01-15T12:00:00.000Z';\n  if (format === 'date') return '2026-01-15';\n  if (format === 'email') return 'user@example.com';\n  if (format === 'uri' || format === 'url') return 'https://example.com';\n  if (format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n\n  const suffix = seed > 0 ? String(seed) : '';\n  let value = STRING_SAMPLE;\n  const minLength = Math.min(constraints?.minLength ?? 0, MAX_GENERATED_LENGTH);\n  if (value.length + suffix.length < minLength) {\n    const missing = minLength - value.length - suffix.length;\n    value += STRING_SAMPLE.repeat(Math.ceil(missing / STRING_SAMPLE.length)).slice(0, missing);\n  }\n  const maxLength = constraints?.maxLength;\n  if (maxLength !== undefined && value.length + suffix.length > maxLength) {\n    // Keep the distinguishing suffix when there is room for it.\n    value = value.slice(0, Math.max(0, maxLength - suffix.length));\n  }\n  return (value + suffix).slice(0, maxLength ?? Infinity);\n}\n\n/** The tighter of an inclusive and an exclusive bound on one side, and whether that edge is exclusive. */\ninterface Edge {\n  value: number;\n  exclusive: boolean;\n}\n\nfunction edge(inclusive: number | undefined, exclusive: number | undefined, side: 'low' | 'high'): Edge | undefined {\n  if (inclusive === undefined && exclusive === undefined) return undefined;\n  if (inclusive === undefined) return { value: exclusive!, exclusive: true };\n  if (exclusive === undefined) return { value: inclusive, exclusive: false };\n  // Both declared (legal in 3.1): the exclusive one is the tighter edge when\n  // it is at or inside the inclusive one.\n  const exclusiveIsTighter = side === 'low' ? exclusive >= inclusive : exclusive <= inclusive;\n  return exclusiveIsTighter ? { value: exclusive, exclusive: true } : { value: inclusive, exclusive: false };\n}\n\n/**\n * A number inside the declared bounds and on the declared `multipleOf` —\n * see the `ExampleBuilder` doc for the anchor rules. Candidates are tried\n * in order and the first that satisfies every limit wins; only when none\n * does is the lower bound returned as is.\n */\nfunction numberExample(integer: boolean, constraints?: Constraints): number {\n  if (!constraints) return 1;\n  const multipleOf =\n    constraints.multipleOf !== undefined && constraints.multipleOf > 0 ? constraints.multipleOf : undefined;\n  const low = edge(constraints.minimum, constraints.exclusiveMinimum, 'low');\n  const high = edge(constraints.maximum, constraints.exclusiveMaximum, 'high');\n\n  // How far to move off an exclusive edge: the multiple when there is one,\n  // one for integers, half the range when both sides are bounded, else one.\n  const step = multipleOf ?? (integer ? 1 : low && high ? (high.value - low.value) / 2 : 1);\n\n  const pastLow = (): number => {\n    const l = low!;\n    if (multipleOf !== undefined) {\n      const v = ceilToMultiple(l.value, multipleOf);\n      return l.exclusive && v <= l.value ? trim(v + multipleOf) : v;\n    }\n    if (integer) return l.exclusive ? Math.floor(l.value) + 1 : Math.ceil(l.value);\n    return l.exclusive ? trim(l.value + step) : l.value;\n  };\n  const belowHigh = (): number => {\n    const h = high!;\n    if (multipleOf !== undefined) {\n      const v = floorToMultiple(h.value, multipleOf);\n      return h.exclusive && v >= h.value ? trim(v - multipleOf) : v;\n    }\n    if (integer) return h.exclusive ? Math.ceil(h.value) - 1 : Math.floor(h.value);\n    return h.exclusive ? trim(h.value - step) : h.value;\n  };\n\n  const candidates: number[] = [];\n  if (low && high) {\n    if (integer) {\n      candidates.push(pastLow());\n    } else {\n      const mid = (low.value + high.value) / 2;\n      candidates.push(multipleOf !== undefined ? roundToMultiple(mid, multipleOf) : trim(mid), pastLow(), belowHigh());\n    }\n  } else if (low) {\n    candidates.push(pastLow());\n  } else if (high) {\n    candidates.push(belowHigh());\n  } else {\n    candidates.push(multipleOf !== undefined ? ceilToMultiple(1, multipleOf) : 1);\n  }\n\n  for (const v of candidates) {\n    if (satisfies(v, constraints, integer, multipleOf)) return v;\n  }\n  // Nothing satisfies every limit at once: contradictory bounds, or no\n  // multiple between them. Fall back to the lower bound rather than inventing\n  // a value that violates every limit; the snippet stays illustrative.\n  if (!low) return candidates[0];\n  const lower = low.exclusive ? trim(low.value + step) : low.value;\n  return integer ? Math.ceil(lower) : lower;\n}\n\nfunction satisfies(v: number, c: Constraints, integer: boolean, multipleOf: number | undefined): boolean {\n  if (!Number.isFinite(v)) return false;\n  if (integer && !Number.isInteger(v)) return false;\n  if (c.minimum !== undefined && v < c.minimum) return false;\n  if (c.exclusiveMinimum !== undefined && v <= c.exclusiveMinimum) return false;\n  if (c.maximum !== undefined && v > c.maximum) return false;\n  if (c.exclusiveMaximum !== undefined && v >= c.exclusiveMaximum) return false;\n  if (multipleOf !== undefined) {\n    const q = v / multipleOf;\n    if (Math.abs(q - Math.round(q)) > 1e-9) return false;\n  }\n  return true;\n}\n\n/** Smallest multiple of `m` that is >= `value`. */\nfunction ceilToMultiple(value: number, m: number): number {\n  return trim(Math.ceil(value / m - 1e-9) * m);\n}\n\n/** Largest multiple of `m` that is <= `value`. */\nfunction floorToMultiple(value: number, m: number): number {\n  return trim(Math.floor(value / m + 1e-9) * m);\n}\n\n/** Nearest multiple of `m` to `value`. */\nfunction roundToMultiple(value: number, m: number): number {\n  return trim(Math.round(value / m) * m);\n}\n\n/** Trim floating-point noise (`0.30000000000000004` → `0.3`). */\nfunction trim(value: number): number {\n  return Number(value.toPrecision(12));\n}\n","import type { GeneratedFile, EmitterContext } from '../engine/types.js';\nimport type { ResolvedOperation } from '../ir/operation-hints.js';\nimport { createExampleBuilder } from './example-builder.js';\nimport type { SnippetEmitter, SnippetResult } from './types.js';\n\n/**\n * Run one or more snippet emitters over every resolved operation in the spec.\n *\n * Iteration order matches `ctx.resolvedOperations`. For each operation the\n * runner asks every emitter to render once; emitters that return `null`\n * contribute nothing for that op (the URL-builder / unsupported case).\n *\n * Returns a flat list of {@link SnippetResult}. Consumers map these to\n * file paths according to their own layout — see\n * {@link snippetResultsToFiles} for a convenience that writes\n * `<outputDir>/<language>/<methodName>-request.<ext>`.\n */\nexport function runSnippetEmitters(emitters: SnippetEmitter[], ctx: EmitterContext): SnippetResult[] {\n  const resolved = ctx.resolvedOperations;\n  if (!resolved || resolved.length === 0) return [];\n\n  const examples = createExampleBuilder(ctx.spec);\n  const results: SnippetResult[] = [];\n\n  for (const op of resolved) {\n    for (const emitter of emitters) {\n      const content = emitter.renderOperation(op, ctx, examples);\n      if (content === null) continue;\n      results.push({\n        language: emitter.language,\n        fileExtension: emitter.fileExtension,\n        operationId: operationIdFor(op),\n        mountTarget: op.mountOn,\n        methodName: op.methodName,\n        content: ensureTrailingNewline(content),\n      });\n    }\n  }\n\n  return results;\n}\n\n/**\n * Convenience: turn snippet results into oagen-style {@link GeneratedFile}s\n * under `<outputDir>/<language>/<methodName>-request.<extension>`.\n *\n * Useful for consumers wired into the standard oagen file-writing pipeline.\n * Docs builds that already have their own per-tag file layout (e.g.\n * `content/reference/{tag}/_code/...`) typically skip this helper and route\n * `SnippetResult.operationId` / `mountTarget` through their own mapping.\n */\nexport function snippetResultsToFiles(results: SnippetResult[], outputDir = 'snippets'): GeneratedFile[] {\n  return results.map((r) => ({\n    path: `${outputDir}/${r.language}/${r.methodName}-request.${r.fileExtension}`,\n    content: r.content,\n    overwriteExisting: true,\n    integrateTarget: false,\n  }));\n}\n\nfunction operationIdFor(op: ResolvedOperation): string {\n  return `${op.mountOn}.${op.methodName}`;\n}\n\nfunction ensureTrailingNewline(s: string): string {\n  return s.endsWith('\\n') ? s : `${s}\\n`;\n}\n","import type { EmitterContext } from '../engine/types.js';\nimport { ConfigError } from '../errors.js';\nimport type { ResolvedOperation, ResolvedWrapper } from '../ir/operation-hints.js';\nimport type { Field, Model, Parameter } from '../ir/types.js';\nimport { toSnakeCase } from '../utils/naming.js';\nimport type { ExampleBuilder } from './example-builder.js';\n\n/**\n * One argument resolved for a call-site snippet. The {@link wireName} stays\n * in the spec's casing so each language emitter can apply its own\n * field/param casing rules (snake_case for Python/Ruby/PHP, PascalCase for\n * Go/.NET, etc.).\n *\n * Path and query params carry their {@link Parameter} so emitters can pick\n * language-specific safe names; body args carry their {@link Field} so\n * emitters can read field-level metadata (deprecated, type details).\n */\nexport interface SnippetArg {\n  /** 'path' | 'body' | 'query' — used by emitters to pick a casing rule. */\n  source: 'path' | 'body' | 'query';\n  /** Spec wire name (e.g. `domain_data`, `client_id`). */\n  wireName: string;\n  /** Pre-computed illustrative value (string, number, array, object, ...). */\n  value: unknown;\n  /** Original parameter for path/query args, null for body fields. */\n  parameter: Parameter | null;\n  /** Original field for body args, null for path/query params. */\n  field: Field | null;\n}\n\n/**\n * Resolve the set of required arguments for a snippet. Body fields are\n * expanded from the request body model; defaults / inferFromClient fields\n * are filtered out (they're injected by the SDK, not the caller).\n *\n * Iteration order: path params, then required body fields, then required\n * query params. Wire-name collisions between body and path are reported in\n * {@link collisionNames} so the emitter can rename whichever side it\n * prefers (e.g. prefix body field with `body_`).\n */\nexport interface CollectedArgs {\n  args: SnippetArg[];\n  /** Body field wire names that also appear as path params. */\n  collisionNames: Set<string>;\n}\n\nexport function collectSnippetArgs(\n  resolved: ResolvedOperation,\n  ctx: EmitterContext,\n  examples: ExampleBuilder,\n): CollectedArgs {\n  const op = resolved.operation;\n  const hidden = hiddenParamSet(resolved);\n  const args: SnippetArg[] = [];\n  const pathWireNames = new Set<string>();\n\n  for (const p of op.pathParams) {\n    if (!p.required) continue;\n    if (hidden.has(p.name)) continue;\n    pathWireNames.add(p.name);\n    args.push({\n      source: 'path',\n      wireName: p.name,\n      value: exampleForParam(p, examples),\n      parameter: p,\n      field: null,\n    });\n  }\n\n  const collisionNames = new Set<string>();\n  const bodyWireNames = new Set<string>();\n  if (op.requestBody?.kind === 'model') {\n    const bodyModel = findModel(ctx, op.requestBody.name);\n    if (bodyModel) {\n      for (const f of bodyModel.fields) {\n        if (!f.required || f.deprecated) continue;\n        if (hidden.has(f.name)) continue;\n        if (pathWireNames.has(f.name)) collisionNames.add(f.name);\n        bodyWireNames.add(f.name);\n        args.push({\n          source: 'body',\n          wireName: f.name,\n          value: exampleForField(f, examples),\n          parameter: null,\n          field: f,\n        });\n      }\n    }\n  }\n\n  for (const q of op.queryParams) {\n    if (!q.required) continue;\n    if (hidden.has(q.name)) continue;\n    // Some operations (e.g. OAuth-style token endpoints) accept the same field\n    // via both the query string and the request body. The IR keeps both for\n    // wire-format fidelity, but a call site must pass each argument only once,\n    // so skip a query param already emitted as a body field. A query param\n    // that merely shares a path param's name is left intact: path args are\n    // positional and never share the options object, so there is no clash to\n    // resolve (path/body collisions are handled separately via collisionNames).\n    if (bodyWireNames.has(q.name)) continue;\n    args.push({\n      source: 'query',\n      wireName: q.name,\n      value: exampleForParam(q, examples),\n      parameter: q,\n      field: null,\n    });\n  }\n\n  return { args, collisionNames };\n}\n\n/**\n * Build the arg list for a single split (wrapper) variant. The wrapper's\n * `exposedParams` is the contract; fields are looked up on the variant model\n * by exact name and then snake-case-normalized name. Optional status comes\n * from `wrapper.optionalParams` first, then from the field's `required` flag.\n */\nexport function collectWrapperArgs(\n  wrapper: ResolvedWrapper,\n  ctx: EmitterContext,\n  examples: ExampleBuilder,\n): SnippetArg[] {\n  const exactVariantModel = ctx.spec.models.find((m) => m.name === wrapper.targetVariant);\n  // Policies may preserve an SDK acronym such as `MFA` while the parser's\n  // canonical IR name uses `Mfa`. Accept a unique case-only difference, but\n  // never guess when multiple models collide under case folding.\n  const caseInsensitiveMatches = exactVariantModel\n    ? []\n    : ctx.spec.models.filter((m) => m.name.toLowerCase() === wrapper.targetVariant.toLowerCase());\n  const variantModel =\n    exactVariantModel ?? (caseInsensitiveMatches.length === 1 ? caseInsensitiveMatches[0] : undefined);\n  if (!variantModel) {\n    throw new ConfigError(\n      `Snippet wrapper \"${wrapper.name}\" targets unknown model \"${wrapper.targetVariant}\".`,\n      'Set targetVariant to an IR model name after cleanSchemaName/schemaNameTransform has been applied.',\n    );\n  }\n\n  const variantFields = variantModel.fields;\n  const optionalSet = new Set(wrapper.optionalParams);\n  const args: SnippetArg[] = [];\n\n  for (const paramName of wrapper.exposedParams) {\n    const field =\n      variantFields.find((f) => f.name === paramName || toSnakeCase(f.name) === toSnakeCase(paramName)) ?? null;\n    const isOptional = optionalSet.has(paramName) ? true : field ? !field.required : false;\n    if (isOptional) continue;\n    if (!field) {\n      throw new ConfigError(\n        `Snippet wrapper \"${wrapper.name}\" exposes unknown field \"${paramName}\" on model \"${variantModel.name}\".`,\n        'Remove the field from exposedParams or update it to match a field on the targetVariant model.',\n      );\n    }\n    args.push({\n      source: 'body',\n      wireName: paramName,\n      value: examples.forField(field),\n      parameter: null,\n      field,\n    });\n  }\n\n  return args;\n}\n\nexport function hiddenParamSet(resolved: ResolvedOperation): Set<string> {\n  const hidden = new Set<string>();\n  for (const k of Object.keys(resolved.defaults)) hidden.add(k);\n  for (const k of resolved.inferFromClient) hidden.add(k);\n  return hidden;\n}\n\nfunction findModel(ctx: EmitterContext, name: string): Model | undefined {\n  return ctx.spec.models.find((m) => m.name === name);\n}\n\nfunction exampleForParam(p: Parameter, examples: ExampleBuilder): unknown {\n  // example → default → a value generated inside the param's constraints.\n  return examples.forParameter(p);\n}\n\nfunction exampleForField(f: Field, examples: ExampleBuilder): unknown {\n  return examples.forField(f);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqLA,SAAgB,qBAAkC;CAChD,OAAO;EACL,OAAO;GACL,sBAAsB;IAAC;IAAK;IAAK;IAAK;IAAK;GAAG;GAC9C,YAAY;GACZ,wBAAwB;GACxB,gBAAgB;GAChB,SAAS;IACP,cAAc;IACd,YAAY;IACZ,UAAU;IACV,cAAc;GAChB;EACF;EACA,QAAQ;GACN,eAAe;IACb,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;GACP;GACA,iBAAiB;GACjB,iBAAiB;EACnB;EACA,WAAW;GACT,kBAAkB;GAClB,YAAY;GACZ,iBAAiB;EACnB;EACA,YAAY,EACV,iBAAiB,EACnB;EACA,aAAa;GACX,YAAY;GACZ,qBAAqB;EACvB;EACA,SAAS;GACP,SAAS;GACT,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;GACF;EACF;EACA,WAAW;GACT,uBAAuB;GACvB,uBAAuB;GACvB,cAAc;GACd,gBAAgB;IACd;KAAE,QAAQ;KAAe,WAAW;IAAa;IACjD;KAAE,QAAQ;KAAgB,WAAW;IAAS;IAC9C;KAAE,QAAQ;KAAgB,WAAW;IAAQ;IAC7C;KAAE,QAAQ;KAAmB,WAAW;IAAW;IACnD;KAAE,QAAQ;KAAiB,WAAW;IAAU;GAClD;EACF;EACA,cAAc,EACZ,YAAY;GACV;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,EACF;EACA,SAAS,EACP,uBAAuB,GACzB;CACF;AACF;;;;;;AAkBA,SAAgB,iBAAiB,WAAkD;CACjF,OA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