{"version":3,"file":"tree-sitter-DtRfmbzZ.mjs","names":["singularize"],"sources":["../src/ir/types.ts","../src/ir/operation-hints.ts","../src/errors.ts","../src/utils/naming.ts","../src/utils/tree-sitter.ts"],"sourcesContent":["import type { SdkBehavior } from './sdk-behavior.js';\n\n/**\n * Authentication scheme extracted from OpenAPI `components.securitySchemes`.\n *\n * `schemeName` is the key under `components.securitySchemes`, spelled exactly as\n * in the document. The requirements under `ApiSpec.security` and\n * `Operation.security` refer to the same key, so emitters join a requirement to\n * its scheme on that field. `description` is present only when the document\n * declares one.\n */\nexport type AuthScheme = { description?: string; schemeName: string } & (\n  | { kind: 'basic' }\n  | { kind: 'bearer' }\n  | { kind: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n  | { kind: 'oauth2'; flows: Record<string, unknown> }\n);\n\n/**\n * A variable in a templated server URL (`https://{region}.api.example.com`),\n * from the server's `variables` map.\n */\nexport interface ServerVariable {\n  /** Substituted for the placeholder when the caller picks no value; OpenAPI requires one. */\n  default: string;\n  /** The values the variable may take. Present only when the document declares a non-empty list. */\n  enum?: string[];\n  description?: string;\n}\n\n/** A server entry from the OpenAPI servers array */\nexport interface ServerEntry {\n  /**\n   * As written in the document, placeholders included. `ApiSpec.baseUrl` is\n   * the first server's URL with its variables' defaults filled in; resolve any\n   * other entry the same way with `resolveServerUrl` from `ir/server-url.ts`.\n   */\n  url: string;\n  description?: string;\n  /** The template's variables, keyed by placeholder name. Present only when the document declares them. */\n  variables?: Record<string, ServerVariable>;\n}\n\n/**\n * A link to documentation outside the OpenAPI document (an External\n * Documentation Object). Present on a node only when the document declares\n * one with a non-blank `url`; an emitter can surface it in a doc comment (a\n * JSDoc `@see`, say). `url` is exactly as written — OpenAPI allows a value\n * relative to the document's own location, which the parser does not know, so\n * it neither resolves nor rewrites it. `description` is present only when it\n * has non-whitespace content.\n */\nexport interface ExternalDocs {\n  url: string;\n  description?: string;\n}\n\n/**\n * The specification extensions (`x-*` keys) an OpenAPI object declares,\n * each under the key as written with its value verbatim — a string, a\n * boolean, a number, `null`, an array or an object, nested values\n * included — in document order. Carried on `Operation`, `Model`, `Field`\n * and `Enum` as `extensions`, present only when the object declares at\n * least one key the parser does not already read into a typed field (an\n * Operation Object's `x-pagination`, `x-oagen-async`,\n * `x-mutually-exclusive-parameter-groups` and\n * `x-mutually-exclusive-body-groups`; a Schema Object's\n * `x-enum-descriptions` and `x-enumDescriptions`), so an emitter can read\n * the keys it knows (`x-idempotent`, `x-since`) without the parser knowing\n * each one. Not shape: two schemas that differ only in their extensions\n * are one model or one enum wherever the parser decides that, and the\n * differ reports a change to them as additive (`extensionsChanged`,\n * `field-extensions-changed`), never as a type change. Values come from\n * the document unvalidated, so an emitter that writes one into generated\n * source must escape it as it escapes a `description`.\n */\nexport type Extensions = Record<string, unknown>;\n\n/** Root IR node representing the full API surface */\nexport interface ApiSpec {\n  name: string;\n  version: string;\n  description?: string;\n  /** The document's top-level `externalDocs`, when it declares a usable one. */\n  externalDocs?: ExternalDocs;\n  baseUrl: string;\n  servers?: ServerEntry[];\n  services: Service[];\n  /**\n   * The requests the API sends to its users, from the document's top-level\n   * `webhooks` map (OpenAPI 3.1), in document order. Absent — not an empty\n   * list — when the document declares none, so the IR of a document without\n   * webhooks is unchanged. A webhook is not an SDK method: it belongs to no\n   * service, gets no resolved operation name, and is untouched by operation\n   * hints and mount rules. See `Webhook`.\n   */\n  webhooks?: Webhook[];\n  models: Model[];\n  enums: Enum[];\n  auth?: AuthScheme[];\n  /**\n   * Document-level security requirements: the default every operation uses\n   * unless it declares its own `Operation.security`. Same shape and semantics\n   * as that field. `undefined` when the document declares none.\n   */\n  security?: SecurityRequirementSet[];\n  /** Language-agnostic runtime policies (retry, errors, telemetry, etc.). */\n  sdk: SdkBehavior;\n}\n\n/**\n * A request the API sends to its users: one HTTP method of one entry in the\n * document's top-level `webhooks` map (OpenAPI 3.1). An entry whose path item\n * declares several methods yields one `Webhook` per method, so `name` alone\n * does not identify a webhook; `name` + `httpMethod` does.\n *\n * Everything here is read from the receiver's side of the wire: the request\n * body is the payload the receiver is handed, the parameters are the headers\n * (signatures, event types) and query values the request carries, and\n * `responses` are the status codes the sender expects back. An emitter uses\n * this to generate a payload type or a typed handler per event. A webhook is\n * never an SDK method: it has no path, belongs to no `Service`, and gets no\n * resolved operation name.\n *\n * An operation's `callbacks` (OpenAPI 3.x), whose path items have this\n * shape, are read the same way: each is a `Callback`, a `Webhook` tied to\n * the operation that registers it, carried on `Operation.callbacks` — and\n * on `callbacks` here, since a `webhooks` operation may declare its own\n * (#382).\n */\nexport interface Webhook {\n  /** The key under `webhooks`, verbatim (`petAdopted`, `user.created`). */\n  name: string;\n  /**\n   * The operation's `operationId`, verbatim, when the document declares one\n   * that names something: one with no ASCII letter or digit once its trailing\n   * overload markers are stripped (`' '`, `'-'`, `'[1]'`, `'[1][2]'`) is left\n   * out, as `''` is and as on an `Operation`, and the webhook's models are\n   * named from its key (#564). No `operationIdTransform` is applied to it.\n   */\n  operationId?: string;\n  httpMethod: HttpMethod;\n  /**\n   * The `summary` alone, read as `Operation.summary` is: the operation's own,\n   * else the path item's. Absent when neither has content.\n   */\n  summary?: string;\n  /**\n   * The `description` alone, read as `Operation.description` is: the\n   * operation's own, else the path item's, never built from the summary (a\n   * `description` identical to the `summary` is kept in both). Absent when\n   * neither has content.\n   */\n  description?: string;\n  /**\n   * The operation's own `externalDocs`, when it declares a usable one, as on\n   * `Operation.externalDocs`. A Path Item Object has no `externalDocs`, so\n   * there is nothing to fall back to.\n   */\n  externalDocs?: ExternalDocs;\n  /** Present, and `true`, only when the document marks the webhook deprecated. */\n  deprecated?: boolean;\n  /** The operation's `tags`, read exactly as `Operation.tags` is. */\n  tags?: string[];\n  /** Header parameters the request carries, typed like `Operation.headerParams`. */\n  headerParams: Parameter[];\n  /** Query parameters the request carries, typed like `Operation.queryParams`. */\n  queryParams: Parameter[];\n  /** Cookie parameters; present only when the document declares at least one. */\n  cookieParams?: Parameter[];\n  /**\n   * The payload the receiver is handed. An inline object schema is\n   * materialized as a model named `<Stem>Payload`, where the stem is the\n   * `operationId` when there is one and the webhook's name otherwise (see the\n   * parser's `resolveWebhookModelStems` for how the stem is kept unique).\n   * Read from the content entry the same pick as `Operation.requestBody`\n   * chooses, by media type essence. Absent when the operation declares no\n   * `requestBody`, or one none of whose media types is read — which the\n   * parser warns about.\n   */\n  requestBody?: TypeRef;\n  /** How the payload is encoded, read like `Operation.requestBodyEncoding`. */\n  requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text';\n  /**\n   * The media type the payload was read from, by essence, read like\n   * `Operation.requestBodyContentType` (`application/merge-patch+json`;\n   * `application/json` for `application/json; charset=utf-8`): what the\n   * sender labels the request with, so a handler can check it. Present\n   * exactly when `requestBody` is.\n   */\n  requestBodyContentType?: string;\n  /**\n   * Present, and `true`, only when the document marks the request body\n   * `required` and the body declares a media type (`requestBodyContentTypes`\n   * is set), the presence rule `Operation.requestBodyRequired` follows: a\n   * payload carried in `requestBodyContents` alone keeps it, and a body with\n   * no `content`, or an empty map, has no entry.\n   */\n  requestBodyRequired?: boolean;\n  /**\n   * Doc text for the payload, read as `Operation.requestBodyDescription`\n   * is: the Request Body Object's own `description`, else the `description`\n   * written on the schema of the content entry `requestBody` is read from (a\n   * `$ref` is not followed; a nullable `oneOf`/`anyOf` or a single-member\n   * `allOf`, `oneOf` or `anyOf` is read to its branch, its own text first,\n   * an `allOf` member that declares no type being part of the wrapper, #555; a\n   * `oneOf`/`anyOf` of consts read as an enum is read as itself, never to a\n   * variant, #535). Present only when one of the two has non-whitespace\n   * content, kept verbatim.\n   */\n  requestBodyDescription?: string;\n  /**\n   * Media types the payload declares under `content`, in document order and\n   * exactly as written, read as `Operation.requestBodyContentTypes` is.\n   * Present only when at least one is declared.\n   */\n  requestBodyContentTypes?: string[];\n  /**\n   * One entry per `requestBodyContentTypes` entry, in the same order, typed\n   * as `Operation.requestBodyContents` is: the entry for the media type\n   * `requestBody` was read from carries that same TypeRef; an inline object\n   * under another media type is materialized as `<Stem><MediaType>Payload`\n   * (`PetAdoptedTextCsvPayload`). Present only when `requestBodyContentTypes`\n   * is.\n   */\n  requestBodyContents?: RequestBodyContent[];\n  /**\n   * The responses the sender expects from the receiver, in document order:\n   * one entry per status code key (three digits, 100–599) the operation\n   * declares. `default`, range (`2XX`) and `x-` keys are not carried; a key\n   * that is none of those (`error`, `6XX`, `600`) is ignored with a warning.\n   * An entry at a status code that is not an object — `200: \"oops\"`,\n   * `null`, `7` — is no Response Object and no Reference Object: it is\n   * skipped with one warning naming the site (`200 response of\n   * webhooks.petAdopted.post is not a Response Object (\"oops\"); skipping\n   * it.`), as is a `$ref` whose chain ends on a `components/responses` entry\n   * that is not an object (`Gone: []`), the warning naming the component\n   * (`components/responses/Gone (the 200 response of\n   * webhooks.petAdopted.post) is not a Response Object ([]); skipping it.`),\n   * and a `responses` that is not an object at all is read as declaring\n   * none, with a warning (#617); a callback's are read the same way.\n   * Body schemas on these responses are not carried either: a webhook\n   * response is an acknowledgement, and typing it would mint models no\n   * handler needs.\n   */\n  responses: WebhookResponse[];\n  /**\n   * The security the request carries, mirroring the OpenAPI document exactly\n   * as `Operation.security` does: `undefined` inherits `ApiSpec.security`,\n   * `[]` means none, otherwise one alternative per requirement object.\n   */\n  security?: SecurityRequirementSet[];\n  /**\n   * The callbacks the webhook's operation declares, read exactly as\n   * `Operation.callbacks` is: present only when at least one is readable, in\n   * document order. A callback nests through this field in turn, since a\n   * `Callback` is a `Webhook`.\n   */\n  callbacks?: Callback[];\n}\n\n/** One status code a webhook's sender expects back, with the document's description of it. */\nexport interface WebhookResponse {\n  statusCode: number;\n  description?: string;\n}\n\n/**\n * A request the API sends to a URL the caller handed it: one HTTP method of\n * one path item under one runtime expression of one `callbacks` entry\n * (OpenAPI 3.x). Read from the receiver's side exactly as a `Webhook` is —\n * the payload, parameters, responses, docs, deprecation, tags and security\n * are the same fields, read by the same code — and tied to the operation\n * or webhook that registers it through `Operation.callbacks` /\n * `Webhook.callbacks` (#382). A callback has no fixed path: the path item\n * is keyed by a runtime expression the sender evaluates per request, kept\n * verbatim as `expression`. One `callbacks` key may map several expressions\n * to path items, each declaring several methods, so `name` + `expression`\n * + `httpMethod` identifies a callback, and that triple is what `oagen\n * diff` keys its `callback-added` / `callback-removed` / `callback-modified`\n * changes on. A callback is never an SDK method, as a webhook is not.\n *\n * Its payload is materialized as `<Stem>Payload` where the stem is the\n * callback operation's `operationId` when it declares one that names\n * something and no other callback operation declares the same, else the\n * owner's stem followed by the key PascalCased — `createPet`'s `petAdopted`\n * mints `CreatePetPetAdoptedPayload` (see the parser's `extractCallbacks`).\n */\nexport interface Callback extends Webhook {\n  /** The key under the operation's `callbacks` map, verbatim (`petAdopted`). */\n  name: string;\n  /** The runtime expression the path item is keyed by, verbatim (`{$request.body#/callbackUrl}`); a callback has no fixed path. */\n  expression: string;\n}\n\n/**\n * The site a callback is read and reported under, below its owner's\n * `context` — an operation's `operationId` (else `METHOD /path`) or\n * `<service>.<operation>`, a webhook's `webhooks.<key>.<method>`, a parent\n * callback's own: `<context>.callbacks.<name>.<expression>.<method>`\n * (`createPet.callbacks.petAdopted.{$request.body#/callbackUrl}.post`).\n * One format for the parser's warnings and for every walker's diagnostics\n * (#382).\n */\nexport function callbackContext(\n  context: string,\n  callback: Pick<Callback, 'name' | 'expression' | 'httpMethod'>,\n): string {\n  return `${context}.callbacks.${callback.name}.${callback.expression}.${callback.httpMethod}`;\n}\n\n/** A service groups related operations (maps to an SDK resource class) */\nexport interface Service {\n  name: string;\n  description?: string;\n  /**\n   * A document tag's `externalDocs`, resolved by the same rule as\n   * `description`: a service named after a declared tag takes that tag's; a\n   * split-off service inherits it from the first linked tag its operations\n   * carry, chosen independently of the tag its description comes from.\n   * Absent when no tag gives one.\n   */\n  externalDocs?: ExternalDocs;\n  operations: Operation[];\n}\n\n/** One scheme a request must satisfy, with the scopes it needs. */\nexport interface SecurityRequirement {\n  /** Key under `components.securitySchemes`; joins to `AuthScheme.schemeName`. */\n  schemeName: string;\n  scopes: string[];\n}\n\n/**\n * One alternative from an OpenAPI security requirement list: a request must\n * satisfy *every* scheme in the set together (\"all of\"). A list of sets is\n * satisfied by *any one* of them (\"either of\"). An empty set is an alternative\n * that needs no credentials at all, which is how a document makes\n * authentication optional (`security: [{ userToken: [] }, {}]`).\n */\nexport type SecurityRequirementSet = SecurityRequirement[];\n\n/** A single API operation (maps to an SDK method) */\nexport interface Operation {\n  name: string;\n  /**\n   * The operation's `operationId`, verbatim, when the document declares one\n   * that names something: one with no ASCII letter or digit once its trailing\n   * overload markers are stripped — every `[N]` at the end, so `' '`, `'-'`,\n   * `'[1]'` and `'[1][2]'` alike — is left out, as `''` is, and the operation\n   * is path-named. `name` is what the parser made of it\n   * (`operationIdTransform` applied, after the markers are stripped:\n   * `listPets[1][2]` is `listPets`); this says that `name` came from one at\n   * all, which is what `resolveOperations` reads to prefer it over the\n   * path-derived method name. Left out as well when the transform returns a\n   * name that names nothing by the same reading (`''`, `' '`, `'-'`, `'[1]'`),\n   * or no string at all: the operation is path-named, with one warning, as\n   * if the document had declared no `operationId` (#570).\n   */\n  operationId?: string;\n  /**\n   * The `summary` alone: the OpenAPI operation's own, or — when the operation\n   * declares none with non-whitespace content — the `summary` of the Path\n   * Item it sits on (the `paths` entry, or the Path Item a `$ref` entry\n   * leads to), which OpenAPI applies to every operation on that\n   * path. Present only when one of the two has content; a summary that is not\n   * a string, or is empty or whitespace-only, is treated as absent at either\n   * level. `description` below never includes it, so an emitter that\n   * shows the summary — as a one-line label, or above the description —\n   * reads it from here.\n   */\n  summary?: string;\n  /**\n   * The `description` alone, read as `summary` above is: the operation's own,\n   * else the Path Item's. It is never built from the summary, so an operation\n   * that declares only a `summary` has none; a `description` identical to the\n   * `summary` is kept in both, since each is the document's own text. A value\n   * that is not a string, or is\n   * empty or whitespace-only, is treated as absent, and text with content is\n   * kept verbatim.\n   */\n  description?: string;\n  /** The operation's own `externalDocs`, when it declares a usable one. */\n  externalDocs?: ExternalDocs;\n  httpMethod: HttpMethod;\n  path: string;\n  /**\n   * The servers this operation is served from, when they differ from the\n   * document's: the operation's own `servers`, else its Path Item's (OpenAPI\n   * precedence). Absent when the operation inherits `ApiSpec.servers` — it\n   * declares none at either level, or what it declares is the document's list\n   * again (same URLs, descriptions and variables, in the same order), or both\n   * it and the document mean OpenAPI's default server (no servers,\n   * `servers: []`, or nothing but `/`, whatever its description or\n   * variables — `/` references none; `isDefaultServerList` in\n   * `ir/server-url.ts`). Same\n   * shape as `ApiSpec.servers`, variables included, so `resolveServerUrl`\n   * from `ir/server-url.ts` fills a template's defaults the way `baseUrl` was\n   * produced. To find where a request goes, take `op.servers ?? spec.servers`.\n   */\n  servers?: ServerEntry[];\n  pathParams: Parameter[];\n  queryParams: Parameter[];\n  /**\n   * Query parameters the spec also declares as request-body properties on a\n   * body-carrying method (POST/PUT/PATCH). They travel in the body only, so\n   * they are excluded from `queryParams`; they are kept here so inline enums\n   * they declare stay reachable and the compat surface still sees them.\n   * Emitters never serialize these to the URL.\n   */\n  bodyOwnedQueryParams?: Parameter[];\n  headerParams: Parameter[];\n  cookieParams?: Parameter[];\n  /**\n   * The request body's type, read from one content entry of the Request Body\n   * Object (after a `components/requestBodies` `$ref` is resolved). Media\n   * types are matched by essence — parameters and case aside, so\n   * `application/json; charset=utf-8` and `APPLICATION/JSON` are\n   * `application/json` — and tried in a fixed order: `application/json`, then\n   * a `+json` media type (`application/vnd.api+json`; never a range such as\n   * `application/*+json`), then `multipart/form-data`, then\n   * `application/x-www-form-urlencoded`, each\n   * only when it declares a schema; then `application/octet-stream`, then\n   * `text/plain`, with or without one (a schema-less binary body is a binary\n   * string, a schema-less text body a string). An inline object body is\n   * materialized as `<Op>Request`; an inline enum body, or an array of one,\n   * is promoted to `spec.enums` under that name, numbered on a clash with an\n   * enum of other members. Absent when the operation declares no\n   * body, or one none of whose media types is read — which the parser warns\n   * about once, so a body is never dropped silently.\n   */\n  requestBody?: TypeRef;\n  /**\n   * The wire encoding of the media type `requestBody` was read from: `json`\n   * for `application/json` and any concrete `+json` media type, `form-data`\n   * for `multipart/form-data`, `form-urlencoded` for\n   * `application/x-www-form-urlencoded`, `binary` for\n   * `application/octet-stream`, `text` for `text/plain`. Set exactly when\n   * `requestBody` is.\n   */\n  requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text';\n  /**\n   * The media type `requestBody` was read from, by essence — `type/subtype`\n   * with parameters and case stripped: `application/merge-patch+json` for a\n   * body declared under that key, `application/json` for one under\n   * `application/json; charset=utf-8`, `multipart/form-data` for one under\n   * `multipart/form-data; boundary=x`. This is what an emitter sends as the\n   * request's `Content-Type`, so a server that requires its declared media\n   * type accepts the request; parameters such as a multipart boundary are\n   * the emitter's to produce. `requestBodyEncoding` says how to serialize\n   * the body, this says how to label it. The key as written is the\n   * `contentType` of the `requestBodyContents` entry that shares\n   * `requestBody`'s type. Set exactly when `requestBody` is.\n   */\n  requestBodyContentType?: string;\n  /**\n   * Whether a caller must send the request body: the Request Body Object's\n   * `required`, read after a `components/requestBodies` `$ref` is resolved.\n   * OpenAPI defaults the flag to `false`, so a body the document does not\n   * mark required comes through as `false`. Present exactly when\n   * `requestBodyContentTypes` is — whenever the body declares a media type,\n   * whether it is read as `requestBody` or carried in `requestBodyContents`\n   * alone — so it is set beside every `requestBody` but does not imply one;\n   * an operation without a body, or whose body declares no media type, has\n   * no entry.\n   */\n  requestBodyRequired?: boolean;\n  /**\n   * Doc text for the request body, e.g. \"The pet to add to the shelter.\" —\n   * what an emitter prints for the body argument, as `responseDescription`\n   * is what it prints for the return. The Request Body Object's own\n   * `description`, read after a `components/requestBodies` `$ref` is\n   * resolved; when that has no non-whitespace content, the `description`\n   * written on the schema of the content entry `requestBody` is read from,\n   * as it stands there: a `$ref` is not followed, so a component's text\n   * stays on its model, while a `description` written beside the `$ref` is\n   * read; a wrapper the parser collapses or sees through — a nullable\n   * `oneOf`/`anyOf`, a single-member `allOf`, `oneOf` or `anyOf` — is read\n   * to its branch, its own text first, an `allOf` member that declares no\n   * type being part of the wrapper (`allOf: [{ $ref: Pet }, { description }]`\n   * carries that text; #555), while a `oneOf`/`anyOf` of consts\n   * read as an enum, nullable or not, is the schema that declares the\n   * members and is read as itself, never to a variant (#535). When both\n   * have content the body's own wins. The schema's text is also the `description` of the model an\n   * inline object body is materialized as (`<Op>Request`), and the `description` of the `Enum`\n   * an inline enum body is lifted to (`<Op>Request` in `enums`); for a body\n   * no model or enum carries — an inline `oneOf`, an array, a primitive —\n   * this field is the only place that text reaches. Present only when one\n   * of the two has non-whitespace content, kept verbatim. The body's own text is\n   * carried whether or not a media type is read as `requestBody`; the\n   * schema's is read only from the entry that is.\n   */\n  requestBodyDescription?: string;\n  /**\n   * Media types the request body declares under `content`, in document\n   * order and exactly as written (`application/json; charset=utf-8`,\n   * `multipart/form-data; boundary=x`, `text/csv`), so an emitter can offer\n   * each verbatim as a `Content-Type`. Present only when the body declares at\n   * least one media type — whether or not one of them is read as\n   * `requestBody` — as `responseContentTypes` is on the response side.\n   */\n  requestBodyContentTypes?: string[];\n  /**\n   * One entry per `requestBodyContentTypes` entry, in the same order, with\n   * the type that media type resolves to. The entry for the media type\n   * `requestBody` was read from carries that very TypeRef, so the two never\n   * disagree. Every other entry is typed as it would be were it the only one\n   * declared: from its schema when it has one (an inline object materialized\n   * as `<Op><MediaType>Request`, `ReplaceWidgetTextCsvRequest`), else a\n   * binary string for `application/octet-stream`, a string for `text/plain`,\n   * and `unknown` for any other media type. Present only when\n   * `requestBodyContentTypes` is.\n   */\n  requestBodyContents?: RequestBodyContent[];\n  /**\n   * The primary success response's body type: the lowest declared status code\n   * from 200 to 399 whose type is not `unknown` — the lowest 2xx with a typed\n   * body, so a `200` left `unknown` by the media-type rules (a schema-less\n   * `text/csv`) yields to a `201` typed from a schema, and a 3xx entry (always\n   * `unknown`) never wins over a typed 2xx — falling back to the lowest\n   * declared code (an untyped 2xx, or a 3xx when no 2xx is declared).\n   * `responseHeaders` and `responseDescription` come from the same entry.\n   * Never promoted from a `2XX` range or the `default` response: an\n   * operation declaring no 2xx or 3xx response at all (only `default` or\n   * `2XX`, only a `404`, an empty `responses` map, or no `responses` key)\n   * has `{ kind: 'primitive', type: 'unknown' }` here — the type of a body\n   * the document does not describe — with no `responseHeaders` or\n   * `responseDescription`, and an emitter should take the success body\n   * from `rangeResponses` (`2XX`), then `defaultResponse` — the same order\n   * it resolves any status: the explicit entry, then the matching range,\n   * then the default. A body that is itself an inline enum is promoted to\n   * `spec.enums` as `<Op>Response`, and an array of one as `<Op>Item` (see\n   * `SuccessResponse.type` for one of several success bodies).\n   */\n  response: TypeRef;\n  /**\n   * The status code of the response `response` was read from — the primary\n   * success response chosen as described there: `200`; `201` when an untyped\n   * `200` yielded to a typed `201`; `302` for a lone redirect; a POST's lone\n   * `200`. Present exactly when the operation declares at least one 2xx or\n   * 3xx response, and absent when it declares none (only `default`, a range,\n   * 4xx/5xx codes, an empty `responses` map or no `responses` key) — the\n   * case where `response` is `unknown`. When `successResponses` is set, this\n   * equals the `statusCode` of the entry `response` was taken from. Read it\n   * to check or document the status an operation succeeds with instead of\n   * guessing one from the HTTP method. The differ pairs a lone 2xx/3xx with\n   * the other spec's entry of this code, so an entry added beside it is not\n   * mistaken for it, and reports it moving while both specs carry one as\n   * `responseStatusCodeChanged`, breaking unless the new spec still declares\n   * the old code among its 2xx/3xx (#407).\n   */\n  responseStatusCode?: number;\n  /**\n   * Headers the primary success response declares (the one `response` is the\n   * body of). Present only when the spec declares at least one. Each entry of\n   * `successResponses` carries its own `headers`, but that list is only set\n   * when an operation declares more than one 2xx or 3xx response (counted\n   * together), so the primary response's headers need a home of their own.\n   */\n  responseHeaders?: ResponseHeader[];\n  /**\n   * Media types the primary success response declares under `content`, in\n   * document order and exactly as written (`application/json; charset=utf-8`,\n   * `application/vnd.api+json`, a wildcard such as `application/*`). Present\n   * only when it declares at least one. Like `responseHeaders`, this lifts\n   * the primary entry's `contentTypes`, because `successResponses` only\n   * exists when an operation declares more than one 2xx or 3xx response.\n   */\n  responseContentTypes?: string[];\n  /**\n   * One entry per `responseContentTypes` entry, in the same order, with the\n   * type that media type's schema resolves to. The entry for the media type\n   * `response` was read from carries that same TypeRef. Present only when\n   * `responseContentTypes` is.\n   */\n  responseContents?: ResponseContent[];\n  /**\n   * The `description` of the primary success response (the one `response` is\n   * the body of), e.g. \"The pet, with its owner.\" — often the clearest\n   * statement of what an operation gives back, so an emitter can print it as\n   * a `@returns` tag. Present only when that response declares one with\n   * non-whitespace content; the text is kept verbatim. Each entry of\n   * `successResponses` carries its own `description`, but that list is only\n   * set when an operation declares more than one 2xx or 3xx response (counted\n   * together), so the primary response's description needs a home of its own.\n   */\n  responseDescription?: string;\n  /**\n   * Every declared 2xx and 3xx response, one `SuccessResponse` per status\n   * code, each with its own `type`, `headers` and `description`. A 2xx entry's\n   * `type` is its body, read by media type compared by essence, parameters\n   * and case aside (the JSON schema — `application/json`, else a `+json`\n   * media type; else binary string for `application/octet-stream` /\n   * `application/pdf`; else `string` for `text/plain`, `text/html`,\n   * `text/xml`, `application/xml`; else the schema of the first media type\n   * that declares one) and `unknown` when none applies, a schema-less\n   * `text/csv` included; a 3xx entry's `type` is always\n   * `unknown`, and the entry is kept so an emitter can\n   * recognize a redirect endpoint. Set only when more than one such response\n   * is declared, counting 2xx and 3xx together: `200` + `201`, `200` + `302`\n   * and `301` + `302` all set it, while a lone `200` (or a lone `302`) leaves\n   * it `undefined` and `response` / `responseHeaders` / `responseDescription`\n   * describe that single response alone. 4xx and 5xx responses go to\n   * `errors`; `default` and the ranges `1XX`–`5XX` to `defaultResponse` and\n   * `rangeResponses`; an explicit 1xx code is not carried. A key is a status\n   * code only when it is exactly three digits in 100–599: `6XX`, `4XXX`,\n   * `20X`, `600` and `200 ` are no status code and no range, so they are\n   * ignored with a warning, like `error`, never read from a numeric prefix.\n   * An entry that is not an object — `200: \"oops\"`, `null`, `7`, `true`,\n   * `[]` — under any key a reader reads (a status code, `default`, a range)\n   * is no Response Object and no Reference Object: it is skipped with one\n   * warning naming the site (`200 response of listPets is not a Response\n   * Object (\"oops\"); skipping it.`) and the operation is read from its other\n   * entries, so `listPets` with `200: \"oops\"` beside a `204` is read from\n   * the `204`, with no entry here, in `errors`, `defaultResponse` or\n   * `rangeResponses` for the skipped key; a `$ref` whose chain ends on a\n   * `components/responses` entry that is not an object (`Gone: []`) is\n   * skipped the same way, the warning naming the component\n   * (`components/responses/Gone (the 200 response of listPets) is not a\n   * Response Object ([]); skipping it.`), so the inline and `$ref`\n   * spellings give one IR; a `responses` that is not an object at all is\n   * read as absent, with a warning (#617).\n   */\n  successResponses?: SuccessResponse[];\n  errors: ErrorResponse[];\n  /**\n   * The document's `default` response: what the operation returns for every\n   * status it does not list explicitly or by range. Present only when the\n   * spec declares one. It is kept apart from `errors` because it carries no\n   * status code (`ErrorResponse.statusCode` is a number emitters compare and\n   * format as one) and is not always an error — a spec may use it for its\n   * success body too. An emitter should treat its `type` as the fallback for\n   * any status that neither `errors`/`successResponses` nor `rangeResponses`\n   * covers. `response` is never promoted from it: when the operation declares\n   * no explicit 2xx, the emitter takes the success body from the `2XX` entry\n   * of `rangeResponses`, then from here.\n   */\n  defaultResponse?: DefaultResponse;\n  /**\n   * The document's `1XX`–`5XX` range responses, in declaration order. Present\n   * only when the spec declares at least one. A range covers every status in\n   * its hundred that the operation does not list explicitly, so an emitter\n   * resolves a status in the order OpenAPI does: the explicit entry, then\n   * the range, then `defaultResponse`. Ranges never feed `response`,\n   * `successResponses` or `errors`, whose numeric `statusCode` could not say\n   * which codes an entry stands for.\n   */\n  rangeResponses?: RangeResponse[];\n  pagination?: PaginationMeta;\n  injectIdempotencyKey: boolean;\n  deprecated?: boolean;\n  async?: boolean;\n  /**\n   * The operation's `tags`, in document order, with every entry that is not\n   * a string with non-whitespace content dropped and a repeated entry folded\n   * onto its first occurrence. Present only when at least one remains. The\n   * parser names the service from the first entry that still has a name once\n   * PascalCased (`tags[0]`, unless it has no ASCII letter or digit, like\n   * `-`), or from the path when none has one, as for an untagged operation;\n   * the list is kept so an emitter can group or document the method by every\n   * tag.\n   */\n  tags?: string[];\n  /**\n   * Per-operation security requirements, mirroring the OpenAPI document:\n   * - `undefined` — the operation declares nothing and inherits\n   *   `ApiSpec.security` (which may itself be `undefined`).\n   * - `[]` — `security: []`: the operation needs no authentication.\n   * - otherwise one `SecurityRequirementSet` per requirement object; the\n   *   request must satisfy any one set, and every scheme within it.\n   */\n  security?: SecurityRequirementSet[];\n  /**\n   * Mutually-exclusive parameter groups parsed from `x-mutually-exclusive-parameter-groups`.\n   * Each group represents a logical choice the caller must (or may) make between\n   * several subsets of query/path/header parameters. The grouped parameters remain\n   * in their original arrays (queryParams, pathParams, etc.) for wire-format purposes;\n   * this field adds the grouping metadata so emitters can render sum types.\n   */\n  parameterGroups?: ParameterGroup[];\n  /**\n   * The Operation Object's own `x-*` keys (see `Extensions`), less the ones\n   * the parser reads into typed fields: `x-pagination` (`pagination`),\n   * `x-oagen-async` (`async`), `x-mutually-exclusive-parameter-groups` and\n   * `x-mutually-exclusive-body-groups` (`parameterGroups`). A Path Item\n   * Object's extensions are not read. Present only when at least one key\n   * remains.\n   */\n  extensions?: Extensions;\n  /**\n   * The requests the API sends back to URLs the caller supplied, from the\n   * Operation Object's `callbacks` map (OpenAPI 3.x), each read as a\n   * `Webhook` is (see `Callback`; #382). Present only when the operation\n   * declares at least one readable callback, in document order: `callbacks`\n   * key order, then expression order within each Callback Object, then the\n   * path item's method order. A callback is not an SDK method: it belongs\n   * to no service, gets no resolved operation name, and is untouched by\n   * operation hints and mount rules; an emitter types its payload, or a\n   * handler for it, beside the operation. Its models are named from this\n   * operation's stem (`CreatePetPetAdoptedPayload`) and assigned to this\n   * operation's service, as the operation's own are.\n   */\n  callbacks?: Callback[];\n}\n\n/**\n * A mutually-exclusive parameter group. The caller must supply exactly one\n * variant (when `optional` is false) or may omit the group entirely (when true).\n */\nexport interface ParameterGroup {\n  /** Group name from the extension (e.g. \"parent_resource\"). */\n  name: string;\n  /** True when the whole group may be omitted. */\n  optional: boolean;\n  /** Ordered variants (insertion order matches the spec). */\n  variants: ParameterGroupVariant[];\n  /**\n   * Base name emitters must use for this group's generated wrapper type, in\n   * place of `name`.\n   *\n   * Two operations commonly share one group name — create and update both\n   * declare `protocol_options` — and emitters name the wrapper from the group\n   * name alone, so both operations collapse onto one type. That is correct\n   * only while their members agree. When they disagree (create's\n   * `saml_options` is a `CreateConnectionSAMLOptions`, update's is a\n   * `PatchConnectionSAMLOptions`) one wrapper silently forces one operation to\n   * use the other operation's type.\n   *\n   * The parser therefore fingerprints each group's members across every\n   * operation declaring it and qualifies this with the operation name\n   * (`update_connection_protocol_options`) only where they genuinely diverge.\n   * Groups that agree — including ones differing only by nullability, or by\n   * duplicate inline enums carrying identical values — keep the bare group\n   * name, so already-published wrapper types are never renamed.\n   */\n  wrapperName?: string;\n}\n\n/**\n * One variant within a mutually-exclusive parameter group.\n */\nexport interface ParameterGroupVariant {\n  /** Variant name from the extension (e.g. \"by_id\", \"by_external_id\"). */\n  name: string;\n  /**\n   * References to the actual parameter IR nodes. These are the same\n   * objects that live in operation.queryParams / .pathParams / .headerParams --\n   * shared by identity, not duplicated.\n   */\n  parameters: Parameter[];\n  /**\n   * Names of parameters that may be omitted when this variant is used —\n   * optional modifiers of the variant's required fields, from the\n   * extension's `optionalFields`. Absent means every parameter in the\n   * variant is required with it.\n   */\n  optionalParameters?: string[];\n}\n\n/**\n * How an operation's list is paged — what an auto-paging iterator sends to\n * reach the next page:\n *\n * - `cursor` — `param` carries an opaque cursor taken from the previous\n *   response; iteration ends when the response yields no next cursor.\n * - `offset` — `param` is the number of items to skip; advance it by the\n *   number of items received, with `limitParam` as the page size.\n * - `page` — `param` is a page *number*; start at `pageStart` (the\n *   parameter's `default`, else its `minimum`, else 1) and advance it by\n *   exactly one per request, with `limitParam` as the page size.\n * - `link-header` — follow the RFC 5988 `Link: <…>; rel=\"next\"` response\n *   header instead of building the next request from `param`.\n *\n * Under every strategy an empty page ends the iteration; `endOfIteration`\n * names a response field that ends it earlier.\n */\nexport type PaginationStrategy = 'cursor' | 'offset' | 'page' | 'link-header';\n\n/**\n * The response field that tells an iterator the last page has been reached.\n * `path` is a dotted property path from the response root, in the convention\n * `dataPath` uses: `has_more` at the top level, `pagination.totalPages` one\n * level down inside the pagination companion.\n *\n * - `hasMore` — a boolean; stop when it is `false`.\n * - `totalPages` — an integer count of pages; stop once the pages fetched so\n *   far reach it. For the `page` strategy that is\n *   `page - pageStart + 1 >= totalPages` — `page >= totalPages` when pages\n *   start at 1, `page + 1 >= totalPages` when they start at 0 — for\n *   `offset` it is `floor(offset / limit) + 1 >= totalPages`, and for\n *   `cursor`, whose opaque cursor carries no page number, it is the number\n *   of requests made so far `>= totalPages`.\n * - `totalCount` — an integer count of items; stop once the items received\n *   so far reach it.\n *\n * An empty page ends the iteration under every kind and every strategy.\n */\nexport interface PaginationEndOfIteration {\n  kind: 'hasMore' | 'totalPages' | 'totalCount';\n  path: string;\n}\n\n/**\n * Structured pagination metadata for auto-paging iterator generation.\n *\n * Present only when a query parameter the operation declares drives the\n * iterator — the one detection recognized, or the one an override names —\n * so `param` is always a query parameter of the operation. A list envelope\n * returned by an operation that declares no such parameter (a `page`\n * without a page size, no paging parameter at all) is kept as a plain\n * response model and has no entry here.\n */\nexport interface PaginationMeta {\n  strategy: PaginationStrategy;\n  /** Query parameter that selects the page: the cursor, the offset, or the page number. */\n  param: string;\n  /** Query parameter that sets the page size (`offset` and `page` strategies). */\n  limitParam?: string;\n  /**\n   * First page number the API expects; set for the `page` strategy only. The\n   * page parameter's integer `default`, else its `minimum`, else 1 — read\n   * from the parameter's schema as written, through a `$ref`, `allOf`\n   * members and nullable wrappers — or the value an override sets (an\n   * override may set it under the `page` strategy only). An\n   * iterator sends `pageStart` first and `pageStart + n` after `n` pages;\n   * `PaginationEndOfIteration` shows how the base enters the `totalPages`\n   * stop rule, so emitters never re-derive it.\n   */\n  pageStart?: number;\n  /**\n   * Path to the data array the response was unwrapped on (`data`,\n   * `result.items`); absent when the response is the array itself. The\n   * property is the array in every spelling a field is typed as one:\n   * written as an array, under a nullable wrapper or an `allOf` read as\n   * its member, a `$ref` to an array component, or a JSON Pointer deeper\n   * into a component that lands on a schema typed as an array where it\n   * stands (`#/components/schemas/Holder/properties/owners`; #609), read\n   * ahead from the document as the settle will type it — so `response` is\n   * the pointed array once settled and `itemType` its items, the model the\n   * pointed schema's items built, never a copy.\n   */\n  dataPath?: string;\n  /**\n   * The description the document gives the data array property itself — the\n   * one `dataPath` names — so an emitter that documents what a list method\n   * returns can read it here instead of from the document. Like a `Field`'s\n   * `description` it is the property's own text, never the item schema's.\n   *\n   * Present only when the property declares one; absent whenever `dataPath`\n   * is, since there is no property to take it from.\n   */\n  dataDescription?: string;\n  itemType: TypeRef;\n  /**\n   * Every property the list envelope carries besides the data array, in\n   * document order: the pagination companion (`list_metadata`, `pagination`,\n   * `has_more`, …, recognized in any spelling — `pageInfo` as much as\n   * `page_info`) and any discriminant such as `object: \"list\"`. Together\n   * with `dataPath` and `itemType` this is the envelope's full shape, so an\n   * emitter can type what the endpoint returns and read the page details it\n   * needs for the next request without parsing the document itself.\n   *\n   * An inline companion object is lifted to a model. Because the same envelope\n   * recurs on every list endpoint of an API, copies that agree structurally\n   * share one model named from the property alone (`list_metadata` →\n   * `ListMetadata`, or the component schema of that name when one exists); a\n   * copy whose shape differs keeps an operation-qualified name\n   * (`ListUsersListMetadata`) so it can never change another type's shape.\n   *\n   * Absent when the response is a bare array, or when pagination was inferred\n   * from query parameters alone and no envelope was detected.\n   */\n  envelopeFields?: Field[];\n  /**\n   * Where the response says the iteration is over (see\n   * `PaginationEndOfIteration`). Detected from a recognized list envelope\n   * when it carries an obvious field — a boolean `has_more`/`hasMore`, an\n   * integer `total_pages`/`totalPages`, or an integer `total`/`total_count`,\n   * each in any spelling that separates its words (`HasMore`, `has-more`) —\n   * beside the array a nested `dataPath` names (`result.total_pages`), beside\n   * each object the path passes through on its way there, nearest the array\n   * first, at the top level, or one level down inside a pagination companion\n   * object (`pagination.totalPages`), in that order, and the same way from\n   * the body an explicit `dataPath` keeps as a wrapper — a component the\n   * response is a `$ref` to, or an inline body detection did not recognize;\n   * a `hasMore` field is preferred over a\n   * `totalPages` one, which is preferred over a count. The operation's\n   * `x-pagination` extension or its `operationHints` entry can set it\n   * explicitly, to a field of the primary response whose type fits the kind.\n   * Absent when nothing recognizable is declared; an emitter then\n   * stops on an empty page (and, for `cursor`, on a missing next cursor).\n   */\n  endOfIteration?: PaginationEndOfIteration;\n}\n\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace';\n\n/**\n * JSON Schema validation keywords declared directly on a schema, carried so an\n * emitter can document a value's limits (\"at most 100\"), check a value before\n * sending it, or keep a generated example within range. Every member is\n * optional and present only when the document declares it; a schema with no\n * validation keyword has no `constraints` at all.\n *\n * Numeric bounds use the OpenAPI 3.1 / JSON Schema 2020-12 shape, where\n * `exclusiveMinimum` / `exclusiveMaximum` are the bound itself. OpenAPI 3.0\n * spells them as booleans that make `minimum` / `maximum` exclusive; the\n * parser normalizes that form, so `{ minimum: 0, exclusiveMinimum: true }`\n * arrives as `{ exclusiveMinimum: 0 }` with no `minimum`, and a `false` is\n * dropped. Emitters read one shape whichever version produced it.\n *\n * The keywords on the field, parameter or model schema itself are carried,\n * conjoined with those of its inline `allOf` members (a single-member\n * `allOf` is unwrapped by the parser, so its limit is the value's own; a\n * `$ref` member contributes the keywords written beside the reference while\n * the referenced model keeps its own). A nullable wrapper — `oneOf`/`anyOf`\n * with a single non-null, non-`$ref` branch — conjoins that branch's\n * keywords with its own.\n *\n * The types carry them too (#545). Every `TypeRef` the parser builds from a\n * schema it types in place — a `primitive`, `literal`, `array`, `map` or\n * `union` — carries that schema's keywords as `constraints`, read exactly\n * as a field's are: the schema's own conjoined with its `allOf` members'\n * and, through a nullable wrapper, the wrapper's with its branch's (so\n * `nullable` itself carries none; its `inner` does), and for a `$ref` to\n * an array or primitive component the component's and each alias's\n * conjoined with any written beside the reference, as `Field.constraints`\n * conjoins them, and for a JSON Pointer `$ref` deeper into a component\n * (#539) the limits the pointed schema's own type carries, conjoined the\n * same way once the site is settled. A `model` or `enum` reference carries none: the model it\n * names carries its own (`Model.constraints`), and what is written around\n * such a `$ref` is the field's or parameter's alone. So a field's or\n * parameter's `constraints` equal those of its type (under its nullable\n * wrapper) whenever the type can carry them — the field keeps its own copy\n * so an emitter can read a value's limits without descending into its type\n * — and the type carries them where no field could: an array's `items`, a\n * union's variants, a map's values, a response header's or a body's type.\n * `{ type: 'array', items: { type: 'string', pattern: '^tag_' } }` has\n * `{ pattern: '^tag_' }` on its `items`; `anyOf: [{ type: 'string',\n * pattern: '^pet_' }, { type: 'string' }]` has it on its first variant and\n * none on the second, so an emitter can type the two apart\n * (`` `pet_${string}` | (string & {}) ``). A union built from a type list\n * (`type: ['string', 'integer']`) carries the schema's keywords itself and\n * its variants none: each variant is the same schema read as one of its\n * types, so the limits are read from the union for whichever type the\n * value takes.\n *\n * `oagen diff` compares them on every node that carries them, the type's\n * at every level included, and reports each keyword tightened or loosened\n * (`field-constraints-changed`, `param-constraints-changed`,\n * `header-constraints-changed`, `variant-constraints-changed`,\n * `constraintsChanged` on a model), breaking when tightened on a\n * request-facing site (#599; see docs/cli.md).\n */\nexport interface Constraints {\n  /** Inclusive lower bound (`minimum`). */\n  minimum?: number;\n  /** Inclusive upper bound (`maximum`). */\n  maximum?: number;\n  /** Exclusive lower bound as a number; the OAS 3.0 boolean form is normalized to this. */\n  exclusiveMinimum?: number;\n  /** Exclusive upper bound as a number; the OAS 3.0 boolean form is normalized to this. */\n  exclusiveMaximum?: number;\n  /** The value must be an integer multiple of this (`multipleOf`). */\n  multipleOf?: number;\n  /** Minimum string length in characters (`minLength`). */\n  minLength?: number;\n  /** Maximum string length in characters (`maxLength`). */\n  maxLength?: number;\n  /** ECMA-262 regular expression the string must match (`pattern`), verbatim from the document. */\n  pattern?: string;\n  /** Minimum number of array items (`minItems`). */\n  minItems?: number;\n  /** Maximum number of array items (`maxItems`). */\n  maxItems?: number;\n  /** Present, and `true`, when array items must be unique; `uniqueItems: false` restates the default and is dropped. */\n  uniqueItems?: boolean;\n  /** Minimum number of items matching the schema's `contains` (`minContains`). */\n  minContains?: number;\n  /** Maximum number of items matching the schema's `contains` (`maxContains`). */\n  maxContains?: number;\n  /** Minimum number of object properties (`minProperties`). */\n  minProperties?: number;\n  /** Maximum number of object properties (`maxProperties`). */\n  maxProperties?: number;\n  /** Property name → properties that must also be present when it is (`dependentRequired`). */\n  dependentRequired?: Record<string, string[]>;\n}\n\nexport interface Parameter {\n  /**\n   * The name as the document wrote it (`X-Pet-Token`); emitters apply their\n   * own casing. A parameter's identity is its location and name —\n   * `parameterKey` in `ir/parameter-key.ts`, which compares a header's name\n   * case-insensitively (RFC 9110 §5.1) and every other as written. The\n   * parser merges a path item's parameters into its operations on that\n   * identity, and the differ pairs parameters on it.\n   */\n  name: string;\n  /**\n   * The parameter schema's type. The parameter's schema is its `schema` or,\n   * for a parameter declared with a `content` map in its place, the schema\n   * of the entry read from that map: `application/json` or a `+json` media\n   * type when the entry declares a schema, else `text/plain` with or without\n   * one, each matched by media type essence (parameters and case stripped).\n   * A `text/plain` entry without a schema types the parameter as a string;\n   * a map none of whose media types is read does too, with a parser warning\n   * that names them; a `schema` beside a `content` map wins. Every field of\n   * this interface that reads \"the parameter's schema\" reads this schema,\n   * so a parameter declared either way is typed by one rule.\n   *\n   * An inline object schema (a `deepObject` query parameter, say), or an\n   * array, map, union or nullable wrapper holding one, references a model\n   * the parser creates for it, named from the service and parameter\n   * (`PetsFilter`; a header's name lower-cased first, so `X-RateLimit-Meta`\n   * and `x-ratelimit-meta` both reference `PetsXRatelimitMeta`) and\n   * qualified by location or operation when that name already belongs to\n   * another shape (see \"Response Headers\" in docs/architecture/ir-types.md);\n   * a webhook's is named under the webhook's stem. A primitive, a `$ref`, an\n   * inline enum (named the same way) or an array of either is typed as\n   * written.\n   */\n  type: TypeRef;\n  required: boolean;\n  description?: string;\n  deprecated?: boolean;\n  /**\n   * The parameter schema's `externalDocs`, when it declares a usable one;\n   * a schema that is a `$ref` falls back to the component it points at,\n   * the way `description` and `deprecated` do. A Parameter Object has no\n   * `externalDocs` of its own. Absent when neither level gives one.\n   */\n  externalDocs?: ExternalDocs;\n  default?: unknown;\n  /**\n   * A single illustrative value, resolved level by level: the parameter's own\n   * `example` (else the first entry of its `examples` map), then — for a\n   * parameter declared with `content` — the same on the Media Type Object\n   * its schema was read from, then the parameter schema's `example` (else\n   * the first of its `examples` list), then the same on the component schema\n   * its `$ref` points at. A level with neither falls through; an explicit\n   * `null` is kept. Absent when no level gives one.\n   */\n  example?: unknown;\n  /**\n   * Every example value the document gives, in document order: the\n   * parameter's `examples` map of Example Objects (each entry's `value`, with\n   * `$ref`s resolved against `components.examples`), else — for a parameter\n   * declared with `content` — the same map on the Media Type Object its\n   * schema was read from, else the JSON Schema `examples` list on the\n   * parameter's schema, else the list on the component schema its `$ref`\n   * points at. Present only when at least one value exists.\n   */\n  examples?: unknown[];\n  style?: 'form' | 'simple' | 'label' | 'matrix';\n  explode?: boolean;\n  /**\n   * The media type the parameter's value is serialized in: the `content`\n   * key its schema was read from, as written (`application/json;\n   * charset=utf-8`). Present exactly when the parameter is declared with\n   * `content` and the map is read (see `type`) — a schema-less `text/plain`\n   * entry included; absent for a `schema` parameter, and for a `content`\n   * map none of whose media types is read, whose string value is sent as\n   * written (`contentTypes` keeps that map's media types). An emitter that\n   * serializes parameters by `style` and `explode` must instead serialize\n   * such a value in this media type: JSON-encode an `application/json` or\n   * `+json` value, send a `text/plain` value as text. `oagen diff` compares\n   * it by essence — an unread map by the first of its `contentTypes` — and\n   * reports a change as a `param-content-type-changed`, breaking unless both\n   * sides are read from a JSON media type.\n   */\n  contentType?: string;\n  /**\n   * The media types the parameter's `content` map declares: its keys, in\n   * document order and exactly as written. Present when the parameter is\n   * declared with `content` and the map declares at least one media type,\n   * whether or not one of them is read (`contentType` is the one that is),\n   * as `Operation.requestBodyContentTypes` is for a request body; absent for\n   * a `schema` parameter, a `schema` beside the map included. OpenAPI allows\n   * the map one entry. For a map none of whose media types is read, this is\n   * where the media type the document declares the value in is kept: the\n   * value is typed as a string and sent as written, so an emitter has\n   * nothing to encode.\n   */\n  contentTypes?: string[];\n  /**\n   * Validation keywords from the parameter's schema, read as a field's are\n   * (`schemaConstraints`; #545 review): the schema's own conjoined with its\n   * `allOf` members' and a nullable wrapper's with its branch's, level by\n   * level, so a keyword written beside an `allOf` member that writes it too\n   * reads as the field and the type read it (`pattern: '^a'` beside `allOf:\n   * [{ pattern: 'z$' }]` is `{ pattern: '^a' }` on all three, the schema's\n   * own winning as `combineConstraints` keeps it; #587 review); for a `$ref`\n   * to a primitive or array component, or to an alias of an enum component,\n   * every entry's conjoined from the component outward, since no model\n   * carries them (the alias's own above the enum's; #560). When the schema\n   * is a `$ref` to a model or enum, the target's keywords are merged\n   * underneath the parameter's own — the per-value fallback `default` and\n   * `example` use — so a parameter can be read on its own without chasing\n   * the target. Absent when neither declares any. Equal to the limits\n   * `type` carries (under its nullable wrapper) whenever it can carry them\n   * — a JSON Pointer `$ref` deeper into a component included, once the\n   * pointer is settled (see `Field.constraints`) — while a `$ref` to a\n   * model or enum keeps the parameter's own here alone (see `Constraints`).\n   */\n  constraints?: Constraints;\n}\n\n/** Type reference — the core type system of the IR */\nexport type TypeRef = PrimitiveType | ArrayType | ModelRef | EnumRef | UnionType | NullableType | LiteralType | MapType;\n\nexport interface PrimitiveType {\n  kind: 'primitive';\n  type: 'string' | 'integer' | 'number' | 'boolean' | 'unknown';\n  format?: string;\n  /**\n   * The validation keywords of the schema this primitive was built from —\n   * `pattern`, `minLength`, `minimum`, … — read as a field's are and\n   * present only when it declares any (see `Constraints`; #545): a field's\n   * own string, an array's items, a union's variant, a map's values and a\n   * `$ref` to a primitive component (the component's own) alike, so\n   * `items: { type: 'string', pattern: '^tag_' }` is readable from `items`.\n   */\n  constraints?: Constraints;\n}\n\nexport interface ArrayType {\n  kind: 'array';\n  items: TypeRef;\n  /**\n   * The validation keywords of the array schema itself — `minItems`,\n   * `maxItems`, `uniqueItems`, … — read as a field's are and present only\n   * when it declares any (see `Constraints`; #545). The items' own keywords\n   * are on `items`, so a nested array carries each level's where it sits:\n   * `{ type: 'array', minItems: 1, items: { type: 'array', uniqueItems:\n   * true, items: { type: 'string', pattern } } }` is `{ minItems: 1 }`\n   * here, `{ uniqueItems: true }` on `items` and `{ pattern }` on its items.\n   */\n  constraints?: Constraints;\n}\n\nexport interface ModelRef {\n  kind: 'model';\n  name: string;\n}\n\nexport interface EnumRef {\n  kind: 'enum';\n  name: string;\n  values?: (string | number)[];\n}\n\nexport interface LiteralType {\n  kind: 'literal';\n  value: string | number | boolean | null;\n  /** The validation keywords written beside the `const` or single-member `enum`, read as a field's are and present only when it declares any (see `Constraints`; #545). */\n  constraints?: Constraints;\n}\n\nexport interface UnionType {\n  kind: 'union';\n  /**\n   * The variants, in the document's order: a `oneOf`/`anyOf`'s non-null\n   * variants, or — for an OAS 3.1 type list naming several types (`type:\n   * ['object', 'string']`) — one per non-null type in the list's order,\n   * each the schema read as that type alone: keeping the keywords that\n   * apply to an instance of it (`properties` for the object, `items` for\n   * an array, `format` and `pattern` for a string; `const`, `enum` and a\n   * composition for every type) and left out when the schema's\n   * `allOf`/`oneOf`/`anyOf` admits no instance of it (#616). `{ type:\n   * ['object', 'string'], allOf: [{ $ref: Owner }] }` is `Owner | string`\n   * when `Owner` declares `properties` and no `type`, and `Owner` alone —\n   * no union — when `Owner` is `type: 'object'`, which no string\n   * satisfies. Never one type twice: copies typed alike are one variant,\n   * and a lone variant is the type itself.\n   */\n  variants: TypeRef[];\n  /**\n   * When set, the union is discriminated on `property`, and `mapping` names\n   * the variant each value selects. Resolved from the same sources, in the\n   * same order, as a named union's (`Model.discriminator`), from the same\n   * reading of the variants (#568): the spec's own `discriminator.mapping`,\n   * each target as the document spelled it with a leading\n   * `#/components/schemas/` stripped — an inline union's values are not IR\n   * model names, unlike a named union's — except an entry whose target is a\n   * pointer variant's schema, settled with the variant to the model's IR\n   * name as a named union's is (#539); else, under the keyword, each\n   * variant's const on the property paired with the model it is referenced\n   * by, `{}` when any variant pins none or is unnamed; else, for a `oneOf`\n   * without the keyword, the first property the first variant pins whose\n   * values tell every variant apart. A `$ref` variant is named by its\n   * component and its const read from it — through the component's `allOf`\n   * members, a `$ref` member followed to the component it names, and\n   * through a `$ref` on the property to a component pinning one value\n   * (`Cat: { allOf: [{ $ref: CatBase }, …] }` pins what `CatBase` pins;\n   * `kind: { $ref: HamsterKind }` pins what `HamsterKind` does) — the\n   * declaration read as the type builder reads it, at every hop: a `$ref`\n   * to its component, a nullable wrapper to its one variant, an `allOf`\n   * read as one member to that member, then the `const` or one-value\n   * `enum:` written there, so `kind: { allOf: [{ const: 'cat' }] }`,\n   * `kind: { allOf: [{ $ref: HamsterKind }], description }` and a `$ref`\n   * to `RabbitKind: { allOf: [{ $ref: RabbitConst }] }` pin as `kind: {\n   * const: … }` does, in OAS 3.0 and 3.1 alike (#607) — a\n   * variant wrapping one model `$ref` through that reference, an inline\n   * object variant by the model extracted for it, so `oneOf: [{ $ref: Cat },\n   * { $ref: Dog }]` carries `{ cat: \"Cat\", dog: \"Dog\" }` on a field as it\n   * does as a component.\n   * A request body's union carries only the spec's own mapping; a body\n   * that is a `oneOf` of inline objects under the keyword, each pinning the\n   * property by the same reading, is folded into one object instead.\n   */\n  discriminator?: { property: string; mapping: Record<string, string> };\n  /** Which OAS composition keyword produced this union. Emitters can use this to\n   *  distinguish inheritance (allOf) from exclusive union (oneOf) from open union (anyOf). */\n  compositionKind?: 'allOf' | 'oneOf' | 'anyOf';\n  /**\n   * The validation keywords of the union schema itself — written beside\n   * its `oneOf`/`anyOf`, or on a type list's schema — read as a field's are\n   * and present only when it declares any (see `Constraints`; #545). Each\n   * `oneOf`/`anyOf` variant carries its own, so `anyOf: [{ type: 'string',\n   * pattern: '^pet_' }, { type: 'string' }]` has `{ pattern: '^pet_' }` on\n   * its first variant and nothing here, while `{ anyOf: [...], maxLength:\n   * 10 }` has `{ maxLength: 10 }` here. A type list's variants carry none:\n   * `{ type: ['string', 'integer'], maxLength: 20, minimum: 1 }` has both\n   * here, to read for whichever type the value takes.\n   */\n  constraints?: Constraints;\n}\n\n/**\n * A type that admits `null` beside `inner`. Carries no `constraints` of its\n * own: a nullable wrapper's validation keywords are the value's, conjoined\n * onto `inner` as a field's conjoin through the wrapper (see `Constraints`).\n */\nexport interface NullableType {\n  kind: 'nullable';\n  inner: TypeRef;\n}\n\nexport interface MapType {\n  kind: 'map';\n  valueType: TypeRef;\n  keyType?: TypeRef;\n  /**\n   * The validation keywords of the map's object schema itself —\n   * `minProperties`, `maxProperties`, `dependentRequired` — read as a\n   * field's are and present only when it declares any (see `Constraints`;\n   * #545). The values' own keywords are on `valueType`.\n   */\n  constraints?: Constraints;\n}\n\n/**\n * A generic type parameter on a model.\n * Example: `DirectoryUser<TCustomAttributes = Record<string, unknown>>`\n * → `{ name: 'TCustomAttributes', default: { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } } }`\n */\nexport interface TypeParam {\n  name: string;\n  /** Default type when the param is not specified. */\n  default?: TypeRef;\n}\n\n/**\n * Model definition (maps to an SDK model/data class). Every\n * `components/schemas` entry becomes one, except an enum (`Enum`) and an\n * alias of one, an array component and a primitive component. An alias of\n * an enum component — a bare `$ref` to it, a nullable `oneOf`/`anyOf`\n * around that `$ref`, or an `allOf` read as the reference, alone or beside\n * members that only annotate it (`PetKind: { allOf: [{ $ref: Kind }, {\n * description }] }`) — becomes no model and no enum (#560): a `$ref` to it\n * resolves to the enum (`{ kind: 'enum' }`, under `nullable` when the alias\n * or the enum admits null), what the alias declares is read by a field that\n * names it with a bare `$ref` (`Field`), and the enum keeps its own on the\n * `Enum`. An alias is only a chain that ends at a `$ref` to an enum\n * component: a component that declares its enum inside a lone `allOf`\n * member (`Kind: { allOf: [{ type: 'string', enum }], description }`) or\n * inside a nullable `oneOf`/`anyOf` wrapper (`Kind: { oneOf: [{ allOf: [{\n * type: 'string', enum }] }, { type: 'null' }] }`, `Color: { oneOf: [{\n * type: 'string', enum }, { type: 'null' }] }`; #606) is the enum `Kind`\n * or `Color` itself, nullable for the wrapper, never an alias and never a\n * model. An array component — a schema\n * that is an array and declares `items` (a nullable `oneOf`/`anyOf` around\n * one included), or an alias of one (a bare `$ref`, a nullable\n * `oneOf`/`anyOf` around a `$ref`, or an `allOf` of a `$ref` and limits)\n * — becomes no model at all: a `$ref` to it resolves to the array it\n * declares (`{ kind: 'array' }`, under `nullable` when the component admits\n * null), and what its items reference is extracted under `<Component>Item…`.\n * A primitive component — a `string`, `integer`, `number` or `boolean`\n * schema, a `const` of any value, a type list of such primitives\n * (`['string', 'integer']`) or a schema that declares no type at all (`{\n * description: 'Any value.' }`, `{}`, and the same inside an `allOf` whose\n * members each declare none: `{ allOf: [{ description }] }`), nullable in\n * any spelling, or an alias of one — becomes no model either: a `$ref` to\n * it resolves to what it declares, as the same schema written inline is\n * typed — the primitive\n * (`{ kind: 'primitive' }` with its `format`), the literal (`{ kind:\n * 'literal' }`), the union of primitives (`{ kind: 'union' }`) or `unknown`\n * (`{ kind: 'primitive', type: 'unknown' }`), under `nullable` when the\n * component admits null (#512, #569). What either component and its\n * aliases declare beside the items or the type — text, link, flags,\n * limits, `default`, `x-*` keys — is read by a field that names it with a\n * bare `$ref` (`Field`). A component that is only a `$ref` to a component\n * that becomes a model — `CatAlias: { $ref: Cat }`, with or without\n * `description`, `deprecated`, `externalDocs`, limits or `x-*` keys beside\n * the `$ref`, which are the alias's own — is a model of its own carrying\n * `Cat`'s fields, `required` and discriminator, exactly as `CatAlias: {\n * allOf: [{ $ref: Cat }] }` is, through a chain of such aliases (nothing\n * else an alias writes beside its `$ref` — `properties`, `required`, an\n * `allOf`, a union, a `discriminator` — is read, at any hop, as nothing\n * but annotations is read beside any `$ref`; only the `allOf` spelling\n * composes them) and into a component that itself composes; a `$ref` to it resolves to the alias\n * (`{ kind: 'model', name: 'CatAlias' }`), never to `Cat`, at every site,\n * and as a union variant it pins what `Cat` pins (#618: it was a model with\n * no fields). A chain of bare `$ref`s that returns to itself names nothing:\n * each such component is a model with no fields, reported once. The inline\n * schemas the parser materializes — request bodies,\n * responses, union variants, nested objects, array items, map values — are\n * models too.\n */\nexport interface Model {\n  name: string;\n  /**\n   * The schema's own `description`; for a model built from an `allOf` — a\n   * component's, or an inline merge — the wrapper layer's: the schema's\n   * own, else the first `allOf` member's that declares no type (`allOf:\n   * [{ $ref: Base }, { properties: { name } }, { description: 'An owner.'\n   * }]`; #555 review). A typing member's text stays on that member, a\n   * `$ref` member's on its component.\n   */\n  description?: string;\n  /** The schema's `externalDocs`, when it declares a usable one; for an `allOf` model, the wrapper layer's, as `description` is. */\n  externalDocs?: ExternalDocs;\n  /**\n   * Present, and `true`, when the schema this model was built from says\n   * `deprecated: true` — a component, a discriminated-union variant, or an\n   * inline request body, response or field object. Only that schema's own\n   * top-level keyword counts, read as `Field.deprecated` is: a nullable\n   * branch's flag is not read, nor an `allOf` member's that declares a type\n   * (a `$ref` member's stays on the referenced model) — one that declares\n   * none, `{ deprecated: true }` beside the members, is part of the wrapper\n   * and deprecates the model (#555 review) — and a folded `<Name>Json`\n   * model's flag does not deprecate the `<Name>` it collapses into. Absent\n   * otherwise. An inline\n   * schema that shares the name of a model the document declares has no\n   * model of its own: a deprecated schema identical to a live component\n   * keeps its flag on the `Field`, `Parameter`, `ResponseHeader` or envelope\n   * field that wrote it, and a site with no node of its own carries none — a\n   * request body or response, an array's items, a `oneOf` variant, a webhook\n   * payload variant, an error or secondary body — so deprecating only the\n   * items of `Pet.owners` beside a live component of their shape leaves no\n   * trace in the IR, as it leaves none when two inline copies fold. An\n   * inline schema named like a deprecated component shares nothing with it,\n   * whatever its flag: it keeps a model of its own, qualified by its site\n   * (`GetLegacyWidgetWidget` beside a deprecated `Widget`), which carries\n   * the schema's flag, so deprecating the schema flips this flag on that\n   * model and renames nothing (#441).\n   */\n  deprecated?: boolean;\n  fields: Field[];\n  /**\n   * The components a composed component's `allOf` names, one `{ kind:\n   * 'model' }` reference per `$ref` member, in document order, each once:\n   * `Pet: { allOf: [{ $ref: Animal }], properties: { nickname } }` has\n   * `bases: [Animal]`, `allOf: [{ $ref: Animal }, { $ref: Owned }]` has\n   * `[Animal, Owned]`. Each model names only its direct bases: with\n   * `Animal: { allOf: [{ $ref: Living }], … }`, `Animal.bases` is\n   * `[Living]` and `Pet.bases` stays `[Animal]`, since `Animal` already\n   * covers `Living`. A member names the component its reference resolves\n   * to, as the inline merge records a property's origin\n   * (`mergeAllOfMembers`): a bare alias (`Hop: { $ref: Animal }`) is read\n   * as `allOf: [{ $ref: Animal }]`, a model of its own (#618), so it is the\n   * base and `Animal` is its own base in turn, as an `allOf` component\n   * (`Hop: { allOf: [{ $ref: Animal }] }`) is; a nullable alias (`Alias: {\n   * oneOf: [{ $ref: Animal }, { type: 'null' }] }`) declares nothing of its\n   * own, so the base is `Animal`. A `$ref` member\n   * naming an enum, array or primitive component — which builds no model\n   * and contributes nothing to the fields — is no base. A `$ref` member\n   * whose component an earlier member's chain already read declares\n   * nothing more but is a direct base all the same: `allOf: [{ $ref:\n   * Animal }, { $ref: Living }]` over `Animal: { allOf: [{ $ref: Living }]\n   * }` has `[Animal, Living]`, and `[Living, Animal]` the other way\n   * round, the fields it carries naming the first member that declares\n   * them; the same `$ref` twice is one base, a component naming\n   * itself, or an alias of itself, is no base of its own, and two bases a\n   * rename sends to one name (`Bar` beside a `BarJson` folded onto it)\n   * are one, the first kept (`renameModelRefs`). A `…Json`\n   * component folded onto its base carries its bases with its fields,\n   * less one whose own chain reaches the folded model, which would close\n   * a cycle (see `collapseJsonSuffixModels`); and the parser's last pass\n   * (`settleBases`) settles both keys against the models as they end: no\n   * model's chain of bases reaches itself — a base that does, in a cyclic\n   * document or once a fold collapsed it onto a kept model of the same\n   * shape, is dropped — and a base stays a base only while every field\n   * it ends with is on the model either as the model's own declaration,\n   * which overrides the base's, or as the same field, the base's\n   * declaration and not another's (every key; the type as its final\n   * shape, an inline model built under either model as it ends and an\n   * inline enum by its values), so the model is its own fields plus its\n   * bases' and an emitter writing `extends` or an intersection types\n   * every field as `fields` does: two bases declaring one property\n   * differently (`Tagged.tag: string` beside `Kinded.tag: enum [cat,\n   * dog]`) keep at most the one whose declaration the model carries, the\n   * other's fields the model's own, and a fold that loosens a base, or a\n   * model nested under it, after the model took its fields drops that\n   * base. A field carries `inheritedFrom` only while its base stays. A `$ref` member naming a named union — flattened into\n   * the fields or dispatched, as the union's own model reads it — is a\n   * base like any other model. Present exactly when at least one base is\n   * named, on a model built from a component schema (a dispatcher\n   * included); never on a model built from an inline `allOf` — a request\n   * or response body, a field — nor on a dispatcher's variant models.\n   * `fields` stays complete, the inherited fields included, in the order\n   * the members are read, so an emitter that reads neither this key nor\n   * `Field.inheritedFrom` sees the model it always saw; one that reads\n   * them may write `Pet` as `Animal & { nickname?: string }` or `interface\n   * Pet extends Animal` (see `Field.inheritedFrom`). Provenance, not\n   * shape: two models that differ only here are one shape to the differ\n   * and to the parser's fingerprints, and `collectModelTypeRefs` leaves\n   * the references out, while `renameModelRefs` repoints them,\n   * `validateModelRefs` checks them and reachability for emission\n   * (`collectReferencedNames`) chases them, so the base of an emitted\n   * model is emitted; `collectFieldDependencies` does not list them — an\n   * emitter that writes `extends` imports the base itself.\n   */\n  bases?: TypeRef[];\n  /** Generic type parameters. Empty/undefined for non-generic models. */\n  typeParams?: TypeParam[];\n  /**\n   * Set when the model is a named union: a component schema that is itself a\n   * `oneOf`/`anyOf` with no `properties` of its own. One TypeRef per non-null\n   * variant, in document order, built exactly as an inline union's are: a\n   * `$ref` variant is a `model`/`enum` ref, an inline object variant is a ref\n   * to a model extracted for it (named from this model with the inline\n   * variant rules, never this model's own name), a primitive stays a\n   * primitive. A `type: 'null'` variant is dropped, as an inline union lifts\n   * it into a `nullable` wrapper; a Model has no such wrapper. `fields` keeps\n   * the optional merge of the inline variants' properties it always had, so\n   * an emitter that does not read `variants` sees the same model as before.\n   */\n  variants?: TypeRef[];\n  /** Which composition keyword produced `variants`. Present exactly when `variants` is. */\n  compositionKind?: 'oneOf' | 'anyOf';\n  /**\n   * When set, this model is a discriminated union — over its `variants` (a\n   * named `oneOf`/`anyOf` with a `discriminator:` keyword or a const-pinned\n   * property shared by every variant, a `$ref` variant's read from its\n   * component as `UnionType.discriminator` reads it) or over allOf+oneOf variants (where\n   * `variants` is absent and the mapping alone names them: the union a\n   * composed component carries, as an `allOf` member, beside the `allOf`\n   * or beside the component's own `properties`, whose every variant pins\n   * one property to a distinct const — a `$ref` variant's read from its\n   * component — or that the document declares a `discriminator:` for, on\n   * the union or on the component itself). Emitters should generate a\n   * dispatcher (factory) instead of a regular dataclass. The `property`\n   * field is the discriminator key (e.g. \"event\"), and `mapping` maps each\n   * discriminator value to the concrete variant model name (an IR model\n   * name, after `schemaNameTransform`): an inline variant's model, built\n   * for it and named from the const it pins (`PetCat`), or a `$ref`\n   * variant's component (`{ cat: \"Cat\", dog: \"Dog\" }`), which stands for\n   * it (#398). The const is read as `UnionType.discriminator` reads one —\n   * through a `$ref`, a nullable wrapper and an `allOf` read as one member,\n   * at every hop — for the value and the variant's name alike, so `kind:\n   * { allOf: [{ const: 'cat' }] }` dispatches to `PetCat` as `kind: {\n   * const: 'cat' }` does (#607).\n   */\n  discriminator?: {\n    property: string;\n    mapping: Record<string, string>;\n  };\n  /**\n   * Validation keywords declared on the model's own schema — for an object\n   * schema, `minProperties`, `maxProperties` and `dependentRequired`. Absent\n   * when the schema declares none.\n   */\n  constraints?: Constraints;\n  /**\n   * The `x-*` keys of the schema the model was built from (see\n   * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`: a\n   * component's own, or the inline schema's — a request body, a response,\n   * a `oneOf` variant, an object nested in a field, array items, an\n   * `allOf` wrapper's (a member's keys stay on that member, a `$ref`\n   * member's on its component). A nullable `oneOf`/`anyOf` or single-member\n   * `allOf` wrapper the parser collapses carries its keys onto the model\n   * built from its branch, the wrapper's value winning for a key both\n   * declare, as its link rides onto it. Present only when at least one key\n   * remains. Not shape: an inline schema that differs from a model only\n   * here shares that model, which keeps its own keys.\n   */\n  extensions?: Extensions;\n}\n\nexport interface Field {\n  name: string;\n  /**\n   * Optional domain-facing name override. When set, emitters derive the\n   * domain-side identifier (in their own casing) from this instead of `name`,\n   * while serialization still uses `name` for the wire key. Lets an SDK expose\n   * a wire field under a friendlier name (e.g. `connection_type` → `type`)\n   * without changing the API contract. Set via the `fieldHints` config and\n   * honored by any emitter that reads it.\n   */\n  domainName?: string;\n  type: TypeRef;\n  required: boolean;\n  /**\n   * The direct base — an entry of `Model.bases` — this field is taken from\n   * unchanged, as a `{ kind: 'model' }` reference; absent when the model\n   * declares the field itself, or when a declaration of its own — written\n   * beside the `allOf` or in an inline member, before or after the `$ref`\n   * — changes what the base declares, by any key: its type, its\n   * `description`, a `nullable` or `deprecated` flip, or its `required`\n   * (the model requiring a field the base leaves optional). A declaration\n   * the merge sets aside — a later typing one, which the first typing\n   * declaration outranks (`declareProperty`) — changes nothing, and the\n   * field stays the base's. `Pet: { allOf: [{ $ref: Animal }], required:\n   * [name], properties: { name: { type: 'string', enum: [rex, max] },\n   * nickname } }` over `Animal { name?, species? }` carries `name` and\n   * `nickname` without it and `species` with `inheritedFrom: Animal`, so\n   * an emitter can write `Pet` as `Animal & { name: PetName; nickname?:\n   * string }`; `Pet: { allOf: [{ $ref: Animal }], required: [species] }`\n   * carries `species` without it. A field a base inherits in turn names\n   * the direct base: with `Animal: { allOf: [{ $ref: Living }] }`,\n   * `Living`'s `born` is on `Pet` with `inheritedFrom: Animal`. A field\n   * a base's flattened `oneOf`/`anyOf` variants declare is the model's own\n   * (optional on both, with no origin), as a field the model's own\n   * variants declare is. Unchanged means as the document declares it: the\n   * field's `type` is still built under this model's name, so an inline\n   * object `Animal.meta` declares is `AnimalMeta` on `Animal` and\n   * `PetMeta` on `Pet` — the same shape — with `inheritedFrom: Animal`.\n   * Only on a field of a model that carries `bases`. Provenance, not\n   * shape: two fields that differ only here are one shape to the differ\n   * and to the fingerprints; `renameModelRefs` repoints it and\n   * `validateModelRefs` checks it.\n   */\n  inheritedFrom?: TypeRef;\n  /**\n   * The field schema's own `description`; for a bare `$ref` to an array or\n   * primitive component — which names no model to carry the component's\n   * text — the nearest the reference passes on its way to the array or\n   * primitive (an alias's own, else the component's), as `example` falls\n   * back to it. A `$ref` to a model, named union or enum leaves the text on\n   * it; a bare `$ref` to an alias of an enum component reads the nearest\n   * alias's own — an `allOf` member of its that declares no type included —\n   * and leaves the enum's on the enum (#560). Under a wrapper — a nullable\n   * one, an `allOf` read as the reference\n   * (`{ allOf: [{ $ref: PetId }, { description }] }`) — the field documents\n   * itself: the wrapper's text or a member's written beside the `$ref`,\n   * never the component's; the same holds for every annotation, flag, default\n   * and key below, while `constraints` conjoin through a wrapper. An `allOf`\n   * member that declares no type — `{ description }`, `{ deprecated: true }`,\n   * `{ readOnly: true }`, `{ maxLength: 3 }`, `{ 'x-internal': true }` — is\n   * part of the field's schema, whatever the other members: beside a `$ref`\n   * (`{ allOf: [{ $ref: Kind }, { description }] }` is `Kind` with that\n   * text on the field), beside the one member that types the schema\n   * (`{ allOf: [{ type: 'string', enum: [...] }, { description }] }` is the\n   * enum, read as `{ allOf: [{ type: 'string', enum: [...] }], description }`\n   * is; #555) or beside a merge — the schema's own value first, then the\n   * first such member's, for every keyword below.\n   */\n  description?: string;\n  /**\n   * The field schema's own `externalDocs`, when it declares a usable one —\n   * read like `description`: for a `$ref` with an `externalDocs` sibling\n   * (legal in OAS 3.1), the sibling's link, while the referenced model keeps\n   * its own; a bare `$ref` yields none, unless it names an array or\n   * primitive component, or an alias of an enum component, whose link the\n   * field then carries. Absent otherwise. Documentation, not shape: two\n   * fields that differ only here are one shape.\n   */\n  externalDocs?: ExternalDocs;\n  /**\n   * `true` when the field schema says `readOnly: true` — itself, or an\n   * `allOf` member of its that declares no type (`allOf: [{ $ref: Kind },\n   * { readOnly: true }]`; #555) — or when a bare `$ref` names an array or\n   * primitive component that says so, or an alias of it, or of an enum\n   * component, on the way (see `description`). `writeOnly` is read the same\n   * way.\n   */\n  readOnly?: boolean;\n  writeOnly?: boolean;\n  /**\n   * Present, and `true`, when the field schema says `deprecated: true` — a\n   * keyword written beside a `$ref` included, and an `allOf` member that\n   * declares no type (`allOf: [{ $ref: Kind }, { deprecated: true }]`; #555)\n   * — or when a bare `$ref` names an array or primitive component that says\n   * so, or an alias of it, or of an enum component (#560), on the way, since\n   * no model carries that component's or alias's flag. The flag of a model,\n   * named union or enum a `$ref` names stays on it.\n   */\n  deprecated?: boolean;\n  /**\n   * The field schema's own `default`, an explicit `null` included; for a\n   * bare `$ref` to an array or primitive component that declares none, or to\n   * an alias of an enum component, the nearest the reference passes (see\n   * `description`).\n   */\n  default?: unknown;\n  /**\n   * A single illustrative value. The field schema's `example` when present,\n   * otherwise the first entry of its `examples`; when the schema is a `$ref`\n   * with neither, the same taken from the component it points at — for an\n   * array or primitive component, from the nearest level the reference\n   * passes on its way to the array or primitive (an alias's own, else the\n   * component's), as `description` is read; for an alias of an enum\n   * component, the aliases' own first, then the enum's. An explicit `null`\n   * is kept. Absent when no level gives one.\n   */\n  example?: unknown;\n  /**\n   * Every example value the schema gives, in document order, from the JSON\n   * Schema `examples` list (OAS 3.1 deprecates `example` in its favour) —\n   * on the field schema, else on the component its `$ref` points at, an\n   * array or primitive component's read like `example`: the nearest\n   * non-empty list the reference passes on its way to the array, primitive\n   * or enum. Present only when the list has at least one entry.\n   */\n  examples?: unknown[];\n  /**\n   * Validation keywords declared on the field's schema, including any\n   * written beside a `$ref` (OpenAPI 3.1 allows siblings). A `$ref` to a\n   * model, named union or enum adds none, since the referenced node carries\n   * its own limits; a `$ref` to an array or primitive component, which\n   * names no model, conjoins the component's limits and its aliases' with\n   * the field's own (`{ $ref: Tags, maxItems: 3 }` beside `Tags`'s\n   * `minItems: 1, maxItems: 5` is `{ minItems: 1, maxItems: 3 }`), and one\n   * to an alias of an enum component conjoins the aliases' own, the enum's\n   * staying on the enum (#560) — bare\n   * or under a wrapper the type builder reads through, since the wire\n   * enforces them either way and nothing else carries them: `{ allOf: [{\n   * $ref: PetId }, { description }] }` beside `PetId`'s `pattern` carries\n   * that `pattern`, as `{ allOf: [{ $ref: PetId }] }` and `oneOf: [{ $ref:\n   * PetId }, { type: 'null' }]` do. A JSON Pointer `$ref` deeper into a\n   * component (#539) conjoins the same way with the limits the schema it\n   * lands on carries on its own type, once the pointer is settled\n   * (`resolveSchemaPointers`; #545 review): `{ $ref: '#/components/schemas/\n   * Owner/properties/code', maxLength: 3 }` to `{ type: 'string', pattern:\n   * '^own_', maxLength: 8 }` is `{ maxLength: 3, pattern: '^own_' }`, and\n   * the bare pointer `{ maxLength: 8, pattern: '^own_' }`; a pointer to a\n   * property typed as a model or enum adds none, as a `$ref` to a model\n   * does. Absent when no level declares any. Equal to the limits `type`\n   * carries (under its nullable wrapper) whenever it can carry them — a\n   * `$ref` to a model, named union or enum keeps the field's own here\n   * alone — while the limits of an array's items, a union's variants or a\n   * map's values are on those types only (see `Constraints`; #545).\n   */\n  constraints?: Constraints;\n  /**\n   * The field schema's own `x-*` keys (see `Extensions`), less\n   * `x-enum-descriptions` / `x-enumDescriptions`, read like `constraints`:\n   * keys written beside a `$ref` (legal in OAS 3.1) are the field's, a bare\n   * `$ref` yields none — the referenced model, union or enum carries its\n   * own — unless it names an array or primitive component, or an alias of\n   * an enum component, whose keys and its aliases' the field then carries\n   * under its own, the field's winning per key, as it carries that\n   * component's `description`. A property\n   * several `allOf` members always declare is typed by the first typing\n   * declaration, keys included (a typeless one fills in what it leaves\n   * unset); a property only variants declare carries exactly the keys\n   * every declaration as written agrees on, value for value, whether or\n   * not the declarations share one shape — in an inline `allOf` and under\n   * a component (a bare `oneOf` component, a union member of a component\n   * `allOf`) alike. Present only when at least one\n   * key remains. Not shape: two fields that differ only here are one shape.\n   */\n  extensions?: Extensions;\n}\n\n/** Enum definition */\nexport interface Enum {\n  name: string;\n  /**\n   * The enum schema's own `description`: a component enum's, as\n   * `Model.description` is a component model's — the wrapper layer's over\n   * the member's when the component declares its members inside an\n   * `allOf` read as its one typing member (`Kind: { allOf: [{ type:\n   * 'string', enum }], description }`), or the wrapper's over the branch's\n   * when it declares them inside a nullable `oneOf`/`anyOf` wrapper\n   * (`Kind: { oneOf: [{ allOf: [{ type: 'string', enum }, { description\n   * }] }, { type: 'null' }] }`; #606), as its link, `deprecated`,\n   * `default` and keys are read (`enumComponentDeclaration`) — or — for an\n   * enum lifted\n   * from an inline schema on a property, parameter, response header,\n   * request or response body (primary, secondary-media-type, error or\n   * fallback) or webhook parameter or payload, including array items,\n   * `oneOf` variants and a `oneOf` of string consts collapsed into one enum\n   * — the text of the schema that declares its members, read as its\n   * `externalDocs` is: a nullable `oneOf`/`anyOf` or single-member `allOf`\n   * wrapper the parser collapses gives its own text when it has content,\n   * and the branch's own counts only when the wrapper has none. A\n   * Parameter or Header Object's `description` is that parameter's or\n   * header's, never the enum's. Present only when the text has\n   * non-whitespace content, kept verbatim. When several inline schemas lift\n   * to one name, the first lifted gives the text, as it gives the values and\n   * the link, so the key is absent when that schema declared none even if a\n   * later one does. Documentation, not shape: the differ does not report a\n   * change to it, and two inline enums that differ only in it are one enum.\n   */\n  description?: string;\n  values: EnumValue[];\n  /** Spec-level default value (the value of `default:` on the schema). Optional. */\n  default?: string | number;\n  /**\n   * The enum schema's `externalDocs`, when it declares a usable one: a\n   * component enum's own, or — for an enum lifted from an inline schema on a\n   * property, parameter or response header — that schema's. A nullable\n   * wrapper the parser collapses carries its link onto the enum, as it does\n   * onto a model; when several inline schemas lift to one name, the first\n   * lifted gives the link, as it gives the values.\n   */\n  externalDocs?: ExternalDocs;\n  /** Present, and `true`, when the component enum schema says `deprecated: true`; absent otherwise. */\n  deprecated?: boolean;\n  /**\n   * The `x-*` keys of the schema that declares the members (see\n   * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`, which\n   * the values' `description` is read from: a component enum's own, or —\n   * for an enum lifted from an inline schema — that schema's, read as its\n   * `description` and `externalDocs` are: a nullable `oneOf`/`anyOf` or\n   * single-member `allOf` wrapper the parser collapses carries its keys\n   * onto the branch, the wrapper's value winning for a key both declare.\n   * The field the inline schema types carries the same keys when the enum\n   * schema is the field's own schema; under such a collapsed wrapper the\n   * field carries the wrapper's keys alone (see `Field.extensions`), and\n   * the branch's stay on the enum. When several inline schemas lift to one\n   * name, the first lifted gives the keys, as it gives the values. Present\n   * only when at least one key remains. Not shape: two inline enums that\n   * differ only here are one enum.\n   */\n  extensions?: Extensions;\n}\n\n/**\n * One member of an enum. An enum schema is an `enum:` list or a\n * `oneOf`/`anyOf` whose every non-null variant is a string `const` schema\n * (the OAS 3.1 spelling that documents values one by one); both give one\n * `EnumValue` per member, in document order.\n */\nexport interface EnumValue {\n  /** UPPER_SNAKE_CASE form of `value`. */\n  name: string;\n  /** The value as written; a number stays a number. */\n  value: string | number;\n  /**\n   * The value's own documentation: a `const` member's `description`, else\n   * the entry for the value in the enum schema's `x-enum-descriptions` /\n   * `x-enumDescriptions` extension. Present only when that text has\n   * non-whitespace content; absent otherwise.\n   */\n  description?: string;\n  /**\n   * Present, and `true`, when the value's `const` member says\n   * `deprecated: true`; absent otherwise. An `enum:` list has no per-value\n   * keyword, so its values never carry it.\n   */\n  deprecated?: boolean;\n}\n\n/**\n * Exhaustive check helper for TypeRef switches.\n * If a new kind is added to TypeRef, any switch that doesn't handle it\n * will fail to compile because `never` won't accept the unhandled variant.\n *\n * Usage:\n *   switch (ref.kind) {\n *     case 'primitive': ...\n *     case 'array': ...\n *     // If you forget 'literal', TypeScript errors here:\n *     default: assertNever(ref);\n *   }\n */\nexport function assertNever(x: never): never {\n  // Inline to avoid importing from ../errors.js (ir/ is layer 0, must not import upward)\n  const kind = (x as TypeRef).kind;\n  const err = new Error(\n    `Unexpected TypeRef kind: ${kind}\\nHint: If you added a new TypeRef variant, handle it in every switch/case that calls assertNever.`,\n  );\n  err.name = 'InternalError';\n  throw err;\n}\n\n/**\n * The validation keywords `ref` carries (see `Constraints`; #545): its\n * `constraints` for a `primitive`, `literal`, `array`, `map` or `union`,\n * `undefined` for a `model` or `enum` reference, which carries none, and\n * for a `nullable` wrapper, whose `inner` carries the value's. The one\n * read for every kind, so a reader need not know which kinds carry them.\n */\nexport function typeRefConstraints(ref: TypeRef): Constraints | undefined {\n  switch (ref.kind) {\n    case 'primitive':\n    case 'literal':\n    case 'array':\n    case 'map':\n    case 'union':\n      return ref.constraints;\n    case 'model':\n    case 'enum':\n    case 'nullable':\n      return undefined;\n  }\n  return assertNever(ref);\n}\n\n/**\n * Generic depth-first walker for TypeRef trees.\n * Handles recursion into array/nullable/union/map children and provides\n * an exhaustive `assertNever` check so callers don't need to repeat the\n * switch boilerplate.  Supply callbacks only for the leaf kinds you care about.\n */\nexport function walkTypeRef(\n  ref: TypeRef,\n  visitor: {\n    model?: (ref: ModelRef) => void;\n    enum?: (ref: EnumRef) => void;\n    primitive?: (ref: PrimitiveType) => void;\n    literal?: (ref: LiteralType) => void;\n  },\n): void {\n  switch (ref.kind) {\n    case 'model':\n      visitor.model?.(ref);\n      break;\n    case 'enum':\n      visitor.enum?.(ref);\n      break;\n    case 'array':\n      walkTypeRef(ref.items, visitor);\n      break;\n    case 'nullable':\n      walkTypeRef(ref.inner, visitor);\n      break;\n    case 'union':\n      for (const v of ref.variants) walkTypeRef(v, visitor);\n      break;\n    case 'map':\n      if (ref.keyType) walkTypeRef(ref.keyType, visitor);\n      walkTypeRef(ref.valueType, visitor);\n      break;\n    case 'literal':\n      visitor.literal?.(ref);\n      break;\n    case 'primitive':\n      visitor.primitive?.(ref);\n      break;\n    default:\n      assertNever(ref);\n  }\n}\n\n/**\n * Generic depth-first mapper for TypeRef trees.\n * Like walkTypeRef but returns a transformed value instead of void.\n * Handles recursion into array/nullable/union/map children, passing\n * already-mapped child values to the parent callback.\n */\nexport function mapTypeRef<T>(\n  ref: TypeRef,\n  mapper: {\n    primitive: (ref: PrimitiveType) => T;\n    array: (ref: ArrayType, mappedItems: T) => T;\n    model: (ref: ModelRef) => T;\n    enum: (ref: EnumRef) => T;\n    union: (ref: UnionType, mappedVariants: T[]) => T;\n    nullable: (ref: NullableType, mappedInner: T) => T;\n    literal: (ref: LiteralType) => T;\n    map: (ref: MapType, mappedValue: T, mappedKey?: T) => T;\n  },\n): T {\n  switch (ref.kind) {\n    case 'primitive':\n      return mapper.primitive(ref);\n    case 'array':\n      return mapper.array(ref, mapTypeRef(ref.items, mapper));\n    case 'model':\n      return mapper.model(ref);\n    case 'enum':\n      return mapper.enum(ref);\n    case 'union':\n      return mapper.union(\n        ref,\n        ref.variants.map((v) => mapTypeRef(v, mapper)),\n      );\n    case 'nullable':\n      return mapper.nullable(ref, mapTypeRef(ref.inner, mapper));\n    case 'literal':\n      return mapper.literal(ref);\n    case 'map':\n      return mapper.map(\n        ref,\n        mapTypeRef(ref.valueType, mapper),\n        ref.keyType ? mapTypeRef(ref.keyType, mapper) : undefined,\n      );\n    default:\n      return assertNever(ref);\n  }\n}\n\n// --- IR traversal utilities ---\n\n/**\n * Every TypeRef a model owns: each field's type, then each union variant\n * (`Model.variants`). Every pass that walks a model's type refs (reachability,\n * service assignment, ref rewriting and validation, dependency collection,\n * inline-enum promotion, fingerprinting) goes through this so a type reached\n * only through a named union's variant is treated the way a field type is.\n * A model's `bases` and its fields' `inheritedFrom` name the models it is\n * built on, not types it owns — provenance, not shape (#591) — and are left\n * out, so the fingerprints and the differ read a model with and without\n * them as one shape; `renameModelRefs`, `validateModelRefs` and\n * reachability for emission (`collectReferencedNames`) reach them on their\n * own.\n */\nexport function collectModelTypeRefs(model: Model): TypeRef[] {\n  return [...model.fields.map((field) => field.type), ...(model.variants ?? [])];\n}\n\n/**\n * Rename the models a type refers to, in place: every `model` ref under\n * `ref` — at any depth of array, map, nullable and union wrapper — that\n * `renames` maps and `admit` accepts is pointed at the new name, and each\n * `discriminator.mapping` entry of a union follows the variant it belongs\n * to (`mappingEntriesByVariant`), so a mapping never keeps naming a model\n * that was renamed away and never moves off a variant that stayed: beside a\n * `$ref` to `Comp` (`kind: legacy`) an inline variant titled `Comp`\n * (`kind: new`) renamed to `ThingComp` leaves `{ legacy: 'Comp', new:\n * 'ThingComp' }`. Each reference is looked up once, so `{ A → B, B → C }`\n * moves `A` to `B`, never on to `C`. Without an `admit` every reference is\n * renamed, and so is every mapping target `renames` maps, those naming no\n * variant included: a document's own mapping may send a value to a model\n * that is not among the variants, and a fold that removes that model\n * (`FooJson` into `Foo`) must not leave the mapping naming it. Under an\n * `admit` — the parser's merge passes pass one that tells a reference minted\n * for an inline model from an explicit `$ref` to a same-named component —\n * only an entry a moved variant owns follows it, since a target has no\n * identity to admit. Returns whether any reference moved. Every rename site\n * — the merge passes, the shape registry,\n * the list-envelope pass, the Json fold — goes through this or\n * `renameModelRefs`, so every reference kind a rename can touch is rewritten\n * alike: a field's type, a union's variants and mapping, an operation's\n * bodies, pagination types, headers and secondary bodies, a webhook's\n * payload and parameters.\n */\nexport function renameTypeRefModels(\n  ref: TypeRef,\n  renames: ReadonlyMap<string, string>,\n  admit?: (ref: ModelRef) => boolean,\n): boolean {\n  switch (ref.kind) {\n    case 'model': {\n      const renamed = renames.get(ref.name);\n      if (renamed === undefined || (admit && !admit(ref))) return false;\n      ref.name = renamed;\n      return true;\n    }\n    case 'array':\n      return renameTypeRefModels(ref.items, renames, admit);\n    case 'nullable':\n      return renameTypeRefModels(ref.inner, renames, admit);\n    case 'map': {\n      const key = ref.keyType ? renameTypeRefModels(ref.keyType, renames, admit) : false;\n      const value = renameTypeRefModels(ref.valueType, renames, admit);\n      return key || value;\n    }\n    case 'union':\n      return renameVariants(ref.variants, ref.discriminator?.mapping, renames, admit);\n    case 'enum':\n    case 'literal':\n    case 'primitive':\n      return false;\n    default:\n      return assertNever(ref);\n  }\n}\n\n/**\n * Rename the models `variants` refer to, each `mapping` entry following the\n * variant it belongs to. Returns whether any variant moved.\n */\nfunction renameVariants(\n  variants: TypeRef[],\n  mapping: Record<string, string> | undefined,\n  renames: ReadonlyMap<string, string>,\n  admit: ((ref: ModelRef) => boolean) | undefined,\n): boolean {\n  // By name, every entry follows its target; under a filter, only an entry a\n  // moved variant owns.\n  const owned = mapping && admit ? mappingEntriesByVariant(variants, mapping) : undefined;\n  let moved = false;\n  variants.forEach((variant, index) => {\n    if (!renameTypeRefModels(variant, renames, admit)) return;\n    moved = true;\n    const model = variantModel(variant);\n    if (owned && model) for (const value of owned.get(index) ?? []) mapping![value] = model.name;\n  });\n  if (mapping && !admit) renameMappingTargets(mapping, renames);\n  return moved;\n}\n\n/** The model a variant names — directly, or under its nullable wrapper — which its mapping entry targets; none for any other variant. */\nfunction variantModel(variant: TypeRef): ModelRef | undefined {\n  if (variant.kind === 'nullable') return variantModel(variant.inner);\n  return variant.kind === 'model' ? variant : undefined;\n}\n\n/**\n * Which variant each `mapping` entry belongs to, by the variants' positions:\n * a name one variant carries owns every entry naming it (a document's own\n * mapping may send several values to one schema); a name several variants\n * carry — a `$ref` to a component beside an inline variant titled like it —\n * hands the j-th entry naming it to the j-th such variant, since the parser\n * derives one entry per discriminated variant in variant order. A variant's\n * model is read through its nullable wrapper. An entry naming no variant\n * belongs to none and stays as written.\n */\nfunction mappingEntriesByVariant(variants: readonly TypeRef[], mapping: Record<string, string>): Map<number, string[]> {\n  const indexesByName = new Map<string, number[]>();\n  variants.forEach((variant, index) => {\n    const model = variantModel(variant);\n    if (model) indexesByName.set(model.name, [...(indexesByName.get(model.name) ?? []), index]);\n  });\n  const owned = new Map<number, string[]>();\n  const handed = new Map<string, number>();\n  for (const [value, target] of Object.entries(mapping)) {\n    const indexes = indexesByName.get(target);\n    if (!indexes) continue;\n    let index = indexes[0]!;\n    if (indexes.length > 1) {\n      const j = handed.get(target) ?? 0;\n      handed.set(target, j + 1);\n      if (j >= indexes.length) continue;\n      index = indexes[j]!;\n    }\n    owned.set(index, [...(owned.get(index) ?? []), value]);\n  }\n  return owned;\n}\n\n/** Point every target of `mapping` that `renames` maps at the new name: a rename by name, which reaches an entry naming no variant too. */\nfunction renameMappingTargets(mapping: Record<string, string>, renames: ReadonlyMap<string, string>): void {\n  for (const [value, target] of Object.entries(mapping)) {\n    const renamed = renames.get(target);\n    if (renamed !== undefined) mapping[value] = renamed;\n  }\n}\n\n/**\n * Rename the models a model refers to: every `model` ref in its fields' types\n * and its union variants that `renames` maps and `admit` accepts is pointed\n * at the new name (`renameTypeRefModels`, so a union's mapping inside a field\n * follows its variant) — its `bases` and its fields' `inheritedFrom` with\n * them, so a base renamed or folded away is named by its new name, and two\n * bases the rename sends to one name (`Bar` beside a `BarJson` folded onto\n * it) are one base, the first kept, so `bases` names each once (#591,\n * Greptile) — and the model's own `discriminator.mapping` is\n * rewritten with it: without an `admit`, every target `renames` maps, by\n * name — whether it names a variant, a model outside the variants a\n * document's own mapping sends a value to, or a member an allOf+oneOf\n * dispatcher holds in the mapping alone — so a fold that removes a model\n * never leaves a dispatcher naming it; under an `admit`, only an entry a\n * moved variant owns (`mappingEntriesByVariant`), since a target has no\n * identity to admit. Each reference is looked up once, so a map `{ A → B, B → C }`\n * moves `A` to `B`, never on to `C`. The model's own `name` is left to the\n * caller. Every rename and fold site goes through this, so a dispatcher's\n * mapping can never keep naming a model that was renamed away while its\n * variants moved on. Returns whether any reference moved.\n */\nexport function renameModelRefs(\n  model: Model,\n  renames: ReadonlyMap<string, string>,\n  admit?: (ref: ModelRef) => boolean,\n): boolean {\n  let moved = false;\n  for (const field of model.fields) {\n    if (renameTypeRefModels(field.type, renames, admit)) moved = true;\n    if (field.inheritedFrom && renameTypeRefModels(field.inheritedFrom, renames, admit)) moved = true;\n  }\n  if (model.bases) {\n    for (const base of model.bases) if (renameTypeRefModels(base, renames, admit)) moved = true;\n    const named = new Set<string>();\n    const distinct = model.bases.filter((base) => {\n      if (base.kind !== 'model') return true;\n      if (named.has(base.name)) return false;\n      named.add(base.name);\n      return true;\n    });\n    if (distinct.length !== model.bases.length) model.bases.splice(0, model.bases.length, ...distinct);\n  }\n  const mapping = model.discriminator?.mapping;\n  if (model.variants) {\n    if (renameVariants(model.variants, mapping, renames, admit)) moved = true;\n  } else if (mapping && !admit) {\n    renameMappingTargets(mapping, renames);\n  }\n  return moved;\n}\n\n/**\n * Collect all model names referenced (directly or transitively) by a TypeRef.\n */\nexport function collectModelRefs(ref: TypeRef): string[] {\n  const names: string[] = [];\n  walkTypeRef(ref, { model: (r) => names.push(r.name) });\n  return names;\n}\n\n/**\n * Collect all enum names referenced by a TypeRef.\n */\nexport function collectEnumRefs(ref: TypeRef): string[] {\n  const names: string[] = [];\n  walkTypeRef(ref, { enum: (r) => names.push(r.name) });\n  return names;\n}\n\n/**\n * Collect all TypeRef-referenced model and enum names from a model's fields\n * and, for a named union, its variants.\n * Returns { models, enums } sets for generating import statements.\n */\nexport function collectFieldDependencies(model: Model): {\n  models: Set<string>;\n  enums: Set<string>;\n} {\n  const models = new Set<string>();\n  const enums = new Set<string>();\n\n  for (const ref of collectModelTypeRefs(model)) {\n    for (const name of collectModelRefs(ref)) {\n      if (name !== model.name) models.add(name);\n    }\n    for (const name of collectEnumRefs(ref)) {\n      enums.add(name);\n    }\n  }\n\n  return { models, enums };\n}\n\n/**\n * Assign each model to the service that first references it.\n * Models referenced by multiple services are assigned to the first.\n * Models not referenced by any service are unassigned (absent from the map).\n *\n * @param hints - Optional pin overrides keyed by IR model name → IR service\n *   name. Applied after the natural assignment loop. A hint only pins a model\n *   present in THIS `models` slice; the target service is resolved by name\n *   downstream, so a hint pointing at a service outside `services` still lands\n *   the model in the right directory. Callers may pass a PARTIAL slice (e.g.\n *   discriminated-union planning, per-service barrels, or a `--services`-scoped\n *   run), so this function never rejects a hint — typo validation lives in\n *   {@link validateModelHints}, which runs once against the full spec.\n */\nexport function assignModelsToServices(\n  models: Model[],\n  services: Service[],\n  hints?: Record<string, string>,\n): Map<string, string> {\n  const modelToService = new Map<string, string>();\n  const modelNames = new Set(models.map((m) => m.name));\n\n  for (const service of services) {\n    const referencedModels = new Set<string>();\n\n    for (const op of service.operations) {\n      if (op.requestBody) {\n        for (const name of collectModelRefs(op.requestBody)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const name of collectModelRefs(op.response)) {\n        referencedModels.add(name);\n      }\n      for (const param of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        for (const name of collectModelRefs(param.type)) {\n          referencedModels.add(name);\n        }\n      }\n      if (op.pagination) {\n        for (const name of collectModelRefs(op.pagination.itemType)) {\n          referencedModels.add(name);\n        }\n        for (const field of op.pagination.envelopeFields ?? []) {\n          for (const name of collectModelRefs(field.type)) {\n            referencedModels.add(name);\n          }\n        }\n      }\n      for (const error of op.errors) {\n        if (!error.type) continue;\n        for (const name of collectModelRefs(error.type)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const header of collectResponseHeaders(op)) {\n        for (const name of collectModelRefs(header.type)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const { type } of collectResponseBodyTypes(op)) {\n        for (const name of collectModelRefs(type)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const { type } of collectRequestBodyTypes(op)) {\n        for (const name of collectModelRefs(type)) {\n          referencedModels.add(name);\n        }\n      }\n      // A callback's payload and parameters are the operation's too: the\n      // request is tied to it, so its models land in the operation's\n      // service as the operation's own do (#382). A webhook's callbacks\n      // belong to no service, as the webhook does.\n      for (const callback of op.callbacks ?? []) {\n        for (const ref of collectWebhookTypeRefs(callback)) {\n          for (const name of collectModelRefs(ref)) {\n            referencedModels.add(name);\n          }\n        }\n      }\n    }\n\n    // Transitively collect models referenced by the directly-referenced models\n    // (through their fields and, for a named union, its variants)\n    const toVisit = [...referencedModels];\n    while (toVisit.length > 0) {\n      const name = toVisit.pop()!;\n      const model = models.find((m) => m.name === name);\n      if (!model) continue;\n      for (const typeRef of collectModelTypeRefs(model)) {\n        for (const ref of collectModelRefs(typeRef)) {\n          if (!referencedModels.has(ref) && modelNames.has(ref)) {\n            referencedModels.add(ref);\n            toVisit.push(ref);\n          }\n        }\n      }\n    }\n\n    for (const name of referencedModels) {\n      if (!modelToService.has(name)) {\n        modelToService.set(name, service.name);\n      }\n    }\n  }\n\n  if (hints) {\n    for (const [modelName, serviceName] of Object.entries(hints)) {\n      // Only pin models present in THIS slice; an out-of-slice hint is applied\n      // where its own slice is processed. The target service resolves by name\n      // downstream, so it need not appear in this slice's `services`. Genuine\n      // typos are caught up front by validateModelHints against the full spec.\n      if (!modelNames.has(modelName)) continue;\n      modelToService.set(modelName, serviceName);\n    }\n  }\n\n  return modelToService;\n}\n\n/**\n * Validate model-placement hints against the FULL spec. Run once at the start of\n * generation — where the complete model/service universe is known — so typos in\n * `modelHints` fail loud even though {@link assignModelsToServices} is\n * intentionally lenient about the partial slices it may be handed.\n */\nexport function validateModelHints(models: Model[], services: Service[], hints: Record<string, string>): void {\n  const modelNames = new Set(models.map((m) => m.name));\n  const serviceNames = new Set(services.map((s) => s.name));\n  for (const [modelName, serviceName] of Object.entries(hints)) {\n    if (!modelNames.has(modelName)) {\n      const err = new Error(\n        `modelHints: unknown model \"${modelName}\". Hint keys must match an IR model name (post-cleanSchemaName/schemaNameTransform).`,\n      );\n      err.name = 'ConfigError';\n      throw err;\n    }\n    if (!serviceNames.has(serviceName)) {\n      const err = new Error(\n        `modelHints: unknown service \"${serviceName}\" for model \"${modelName}\". Hint values must match an IR service name (PascalCase, derived from the operation's first tag).`,\n      );\n      err.name = 'ConfigError';\n      throw err;\n    }\n  }\n}\n\n/**\n * Collect all model names referenced as request bodies across all services:\n * each operation's `requestBody`, and the body of every other media type it\n * declares (`collectRequestBodyTypes`).\n */\nexport function collectRequestBodyModels(services: Service[]): Set<string> {\n  const result = new Set<string>();\n  for (const service of services) {\n    for (const op of service.operations) {\n      if (op.requestBody) {\n        for (const name of collectModelRefs(op.requestBody)) {\n          result.add(name);\n        }\n      }\n      for (const { type } of collectRequestBodyTypes(op)) {\n        for (const name of collectModelRefs(type)) {\n          result.add(name);\n        }\n      }\n    }\n  }\n  return result;\n}\n\n/**\n * Every response header an operation declares: the primary response's, each\n * alternate success entry's, and each error entry's. The primary list is the\n * same array as its `successResponses` entry when both exist, so it is yielded\n * once. Every pass that walks an operation's type refs (reachability, model\n * assignment, ref rewriting and validation, direction, compat filtering, enum\n * collection) goes through this so a type reached only through a header is\n * treated the way a body or parameter type is.\n */\nexport function collectResponseHeaders(op: Operation): ResponseHeader[] {\n  const result: ResponseHeader[] = [];\n  const seen = new Set<ResponseHeader[]>();\n  const lists = [\n    op.responseHeaders,\n    ...(op.successResponses ?? []).map((r) => r.headers),\n    ...op.errors.map((e) => e.headers),\n    op.defaultResponse?.headers,\n    ...(op.rangeResponses ?? []).map((r) => r.headers),\n  ];\n  for (const list of lists) {\n    if (!list || seen.has(list)) continue;\n    seen.add(list);\n    result.push(...list);\n  }\n  return result;\n}\n\n/**\n * The body type of every fallback response an operation declares: the\n * `default` response's, then each range response's in declaration order,\n * skipping entries that declare no body. Feeds `collectResponseBodyTypes`,\n * which every pass that walks an operation's type refs goes through (as it\n * goes through `collectResponseHeaders` for headers), so a model reached\n * only as the body of a `default` or `4XX` response is materialized,\n * assigned, renamed and validated like a primary response body.\n */\nexport function collectFallbackResponseTypes(op: Operation): TypeRef[] {\n  const result: TypeRef[] = [];\n  if (op.defaultResponse?.type) result.push(op.defaultResponse.type);\n  for (const range of op.rangeResponses ?? []) {\n    if (range.type) result.push(range.type);\n  }\n  return result;\n}\n\n/**\n * Every type reference a webhook carries: its parameters' types, its\n * request body, the payload of every other media type it declares (each\n * `requestBodyContents` entry whose type is not `requestBody`'s own), and\n * — after its own — everything each of its `callbacks` carries, nested\n * callbacks included, since a `Callback` is a `Webhook` (#382). Every pass\n * that walks an operation's type refs (reachability, ref rewriting and\n * validation, the differ's direction index, inline-enum collection) walks a\n * webhook's through this, so a model reached only through a webhook or\n * callback payload or header is treated the way one reached through an\n * operation is, and a field added to `Webhook` later has one place to join.\n */\nexport function collectWebhookTypeRefs(webhook: Webhook): TypeRef[] {\n  const refs: TypeRef[] = [];\n  for (const param of [...webhook.headerParams, ...webhook.queryParams, ...(webhook.cookieParams ?? [])]) {\n    refs.push(param.type);\n  }\n  if (webhook.requestBody) refs.push(webhook.requestBody);\n  for (const content of webhook.requestBodyContents ?? []) {\n    if (content.type !== webhook.requestBody) refs.push(content.type);\n  }\n  for (const callback of webhook.callbacks ?? []) refs.push(...collectWebhookTypeRefs(callback));\n  return refs;\n}\n\n/**\n * Every type reference an operation carries: its parameters' types in every\n * location (the query parameters the body owns included), its request body\n * and the body of every other request media type (`collectRequestBodyTypes`),\n * its primary response and every other success body, every error body, the\n * pagination iterator's item type and envelope fields, every response header\n * (`collectResponseHeaders`), every secondary, fallback and range body\n * (`collectResponseBodyTypes`), and — last — everything each of its\n * `callbacks` carries, through `collectWebhookTypeRefs`, nested callbacks\n * included (#382). The one list for a pass that reserves or\n * collects names across an operation's references — the enum names held\n * before the deferred schemas are named, the names a merge pass must mint\n * around, the names a webhook must step around — as `collectWebhookTypeRefs`\n * is for a webhook's, so a field added to `Operation` later has one place to\n * join and every reader gets the same list. When `successResponses` exists\n * the primary entry's `type` is the very reference `response` carries, so\n * that reference appears twice; a reader that only collects names is\n * unaffected.\n */\nexport function collectOperationTypeRefs(op: Operation): TypeRef[] {\n  const refs: TypeRef[] = [];\n  for (const param of [\n    ...op.pathParams,\n    ...op.queryParams,\n    ...(op.bodyOwnedQueryParams ?? []),\n    ...op.headerParams,\n    ...(op.cookieParams ?? []),\n  ]) {\n    refs.push(param.type);\n  }\n  if (op.requestBody) refs.push(op.requestBody);\n  for (const { type } of collectRequestBodyTypes(op)) refs.push(type);\n  refs.push(op.response);\n  for (const entry of op.successResponses ?? []) refs.push(entry.type);\n  for (const error of op.errors) if (error.type) refs.push(error.type);\n  if (op.pagination) {\n    refs.push(op.pagination.itemType);\n    for (const field of op.pagination.envelopeFields ?? []) refs.push(field.type);\n  }\n  for (const header of collectResponseHeaders(op)) refs.push(header.type);\n  for (const { type } of collectResponseBodyTypes(op)) refs.push(type);\n  for (const callback of op.callbacks ?? []) refs.push(...collectWebhookTypeRefs(callback));\n  return refs;\n}\n\n/**\n * A header a response declares, typed like a parameter. `name` is kept exactly\n * as written in the spec (e.g. `Content-Disposition`); emitters apply their\n * own casing. Header names are case-insensitive (RFC 9110 §5.1), so one\n * response declares each header once: of two keys that differ in case\n * alone, the parser keeps the later (`foldHeaderName` in\n * `ir/parameter-key.ts` decides which keys are one header).\n */\nexport interface ResponseHeader {\n  name: string;\n  /**\n   * The header schema's type. The header's schema is resolved as a\n   * parameter's is (see `Parameter.type`): the Header Object's `schema`\n   * (resolved through `components/headers`) or, in its place, the schema of\n   * the `content` entry read by the same media type rule. A header with\n   * neither, a `text/plain` entry without a schema, or a map none of whose\n   * media types is read — the last with a parser warning — is a string.\n   */\n  type: TypeRef;\n  required: boolean;\n  /** The Header Object's own `description`; the schema's is never the header's. */\n  description?: string;\n  /**\n   * `true` when the Header Object says `deprecated: true`, or the schema\n   * `type` is read from does — on its own keys, or on an `allOf` member of\n   * it that declares no type and so only annotates it (`allOfWrapperLayer`;\n   * #555), as a field reads the flag. Absent otherwise.\n   */\n  deprecated?: boolean;\n  /**\n   * The header schema's `externalDocs`, when it declares a usable one — the\n   * schema `type` is read from, whether the Header Object's `schema` or the\n   * `content` entry's: its own, else the first `allOf` member's that\n   * declares no type and so only annotates the schema (`allOfWrapperLayer`;\n   * #605), so `allOf: [{ type: 'integer' }, { externalDocs }]` gives the\n   * header the link `allOf: [{ type: 'integer' }], externalDocs` does, as it\n   * gives a field, a parameter and the model built from the schema. A\n   * Header Object has no `externalDocs` of its own. Absent otherwise.\n   */\n  externalDocs?: ExternalDocs;\n}\n\nexport interface ErrorResponse {\n  statusCode: number;\n  type?: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /**\n   * Media types declared under `content`, in document order and as written.\n   * `type` is by definition the JSON body (`application/json`, else the first\n   * `+json` media type), so the list is present only when it says something\n   * `type` does not: the error declares another media type, a JSON media type\n   * other than plain `application/json` (`application/problem+json` alone,\n   * `application/json; charset=utf-8`), or a JSON body `type` could not be\n   * read from. An error that declares only `application/json` with a schema\n   * keeps its shape.\n   */\n  contentTypes?: string[];\n  /**\n   * One entry per `contentTypes` entry, in the same order. The entry for the\n   * media type `type` was read from carries the same TypeRef as `type`.\n   * Present only when `contentTypes` is.\n   */\n  contents?: ResponseContent[];\n  /**\n   * The response's `description` as written in the document (e.g. \"Not\n   * found\"). Present only when it has non-whitespace content; kept verbatim.\n   */\n  description?: string;\n}\n\n/**\n * One entry of `Operation.successResponses`: a declared 2xx or 3xx response.\n * A 3xx entry's `type` is always `unknown`. A 2xx body that is itself an\n * inline enum is promoted to `spec.enums` as `<Op>Response`, and an array of\n * one as `<Op>Item`, the name an array body's items take; every entry of one\n * shape derives the same name, so a second body with other members is\n * qualified with its status code (`CheckPetKindResponse202`,\n * `CheckPetKindItem202`), while identical members share one enum.\n */\nexport interface SuccessResponse {\n  statusCode: number;\n  type: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /**\n   * Media types declared under `content`, in document order and as written.\n   * Present only when there is at least one.\n   */\n  contentTypes?: string[];\n  /**\n   * One entry per `contentTypes` entry, in the same order. The entry for the\n   * media type `type` was read from carries that same TypeRef. Present only\n   * when `contentTypes` is.\n   */\n  contents?: ResponseContent[];\n  /**\n   * The response's `description` as written in the document (e.g. \"The pet,\n   * with its owner.\"). Present only when it has non-whitespace content; kept\n   * verbatim.\n   */\n  description?: string;\n}\n\n/**\n * One media type a response declares under `content`, with the type its\n * schema resolves to. `contentType` is kept exactly as written in the spec,\n * parameters and all, so it can be sent back verbatim in an `Accept` header.\n */\nexport interface ResponseContent {\n  contentType: string;\n  type: TypeRef;\n}\n\n/**\n * One media type a request body declares under `content`, with the type it\n * resolves to. `contentType` is kept exactly as written in the spec,\n * parameters and all, so it can be sent verbatim as a `Content-Type`.\n */\nexport interface RequestBodyContent {\n  contentType: string;\n  type: TypeRef;\n}\n\n/**\n * A response body type other than `Operation.response`, with where it comes\n * from for diagnostics.\n */\nexport interface ResponseBodyType {\n  type: TypeRef;\n  /**\n   * The entry it belongs to: `contents.<media type>` for a secondary media\n   * type, `defaultResponse` for the `default` response's body,\n   * `rangeResponses.<range>` (`rangeResponses.4XX`) for a range response's.\n   */\n  source: string;\n}\n\n/**\n * Every response body type an operation declares besides `response`: the\n * bodies of its secondary media types (`collectAlternateResponseContents`,\n * fallback responses' included), then the fallback bodies of its `default`\n * and range responses (`collectFallbackResponseTypes`), and any body a later\n * field adds. The primary type of each alternate 2xx and error entry is not\n * included — walkers reach those through `successResponses[].type` and\n * `errors[].type` where they do today. Every pass that walks an operation's\n * type refs (reachability, model assignment, ref rewriting and validation,\n * direction, compat filtering, enum collection) calls this beside\n * `collectResponseHeaders`, so a new kind of body is reached everywhere by\n * extending this one function.\n */\nexport function collectResponseBodyTypes(op: Operation): ResponseBodyType[] {\n  const result: ResponseBodyType[] = alternateResponseContents(op).map(({ content, source }) => ({\n    type: content.type,\n    source: `${source}.${content.contentType}`,\n  }));\n  if (op.defaultResponse?.type) result.push({ type: op.defaultResponse.type, source: 'defaultResponse' });\n  for (const range of op.rangeResponses ?? []) {\n    if (range.type) result.push({ type: range.type, source: `rangeResponses.${range.range}` });\n  }\n  return result;\n}\n\n/**\n * A request body type other than `Operation.requestBody`, with where it\n * comes from for diagnostics.\n */\nexport interface RequestBodyType {\n  type: TypeRef;\n  /** The entry it belongs to: `requestBodyContents.<media type>`. */\n  source: string;\n}\n\n/**\n * Every request body type an operation declares besides `requestBody`: the\n * bodies of its other media types (`collectAlternateRequestBodyContents`).\n * The request-side twin of `collectResponseBodyTypes`: every pass that walks\n * an operation's type refs (reachability, model assignment, ref rewriting\n * and validation, direction, compat filtering, enum collection) calls this\n * beside it, so a body declared only for a secondary media type is reached\n * everywhere `requestBody` is, and a new kind of request body is reached\n * everywhere by extending this one function.\n */\nexport function collectRequestBodyTypes(op: Operation): RequestBodyType[] {\n  return collectAlternateRequestBodyContents(op).map((content) => ({\n    type: content.type,\n    source: `requestBodyContents.${content.contentType}`,\n  }));\n}\n\n/**\n * Every request content entry whose type is reachable only through it: the\n * entries of `requestBodyContents` other than the one `requestBody` was read\n * from, which shares that very TypeRef and is already reached through\n * `requestBody`. Every entry when no media type was read as `requestBody`.\n * Feeds `collectRequestBodyTypes`, which the walkers call.\n */\nexport function collectAlternateRequestBodyContents(op: Operation): RequestBodyContent[] {\n  return (op.requestBodyContents ?? []).filter((content) => content.type !== op.requestBody);\n}\n\n/**\n * Every response content entry whose type is reachable only through it: the\n * entries of each success, error and fallback response other than the one\n * the response's own `type` was read from, which shares that very TypeRef\n * and is already reached through `response`, `successResponses[].type`,\n * `errors[].type` or `collectFallbackResponseTypes`. The primary list is the\n * same array as its `successResponses` entry when both exist, so it is\n * visited once. Feeds `collectResponseBodyTypes`, which the walkers call.\n */\nexport function collectAlternateResponseContents(op: Operation): ResponseContent[] {\n  return alternateResponseContents(op).map(({ content }) => content);\n}\n\n/** `collectAlternateResponseContents`, each entry with the list it was read from (`contents`, `defaultResponse.contents`, `rangeResponses.4XX.contents`). */\nfunction alternateResponseContents(op: Operation): Array<{ content: ResponseContent; source: string }> {\n  const result: Array<{ content: ResponseContent; source: string }> = [];\n  const seen = new Set<ResponseContent[]>();\n  const owners: Array<{ contents?: ResponseContent[]; type?: TypeRef; source: string }> = [\n    { contents: op.responseContents, type: op.response, source: 'contents' },\n    ...(op.successResponses ?? []).map((entry) => ({ ...entry, source: 'contents' })),\n    ...op.errors.map((entry) => ({ ...entry, source: 'contents' })),\n    ...(op.defaultResponse ? [{ ...op.defaultResponse, source: 'defaultResponse.contents' }] : []),\n    ...(op.rangeResponses ?? []).map((entry) => ({ ...entry, source: `rangeResponses.${entry.range}.contents` })),\n  ];\n  for (const { contents, type, source } of owners) {\n    if (!contents || seen.has(contents)) continue;\n    seen.add(contents);\n    for (const content of contents) if (content.type !== type) result.push({ content, source });\n  }\n  return result;\n}\n\n/**\n * The `default` response: the body and headers for every status the\n * operation does not list. See `Operation.defaultResponse`.\n */\nexport interface DefaultResponse {\n  /**\n   * Response body type: the `application/json` body, else the first `+json`\n   * one; absent when the response declares neither.\n   */\n  type?: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /**\n   * Media types declared under `content`, in document order and as written,\n   * exactly as on `SuccessResponse`. Present only when there is at least one.\n   */\n  contentTypes?: string[];\n  /**\n   * One entry per `contentTypes` entry, in the same order. The entry for the\n   * media type `type` was read from carries that same TypeRef. Present only\n   * when `contentTypes` is.\n   */\n  contents?: ResponseContent[];\n  /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */\n  description?: string;\n}\n\n/** A Responses Object range key, uppercase as OpenAPI writes it (`4xx` is read as `4XX`). */\nexport type StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\n\n/**\n * A range response: the body and headers for every status in one hundred\n * (`4XX` → 400–499) that the operation does not list explicitly. See\n * `Operation.rangeResponses`.\n */\nexport interface RangeResponse {\n  range: StatusRange;\n  /**\n   * Response body type: the `application/json` body, else the first `+json`\n   * one; absent when the response declares neither.\n   */\n  type?: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /** Media types declared under `content`, as on `DefaultResponse`. */\n  contentTypes?: string[];\n  /** One entry per `contentTypes` entry, as on `DefaultResponse`. */\n  contents?: ResponseContent[];\n  /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */\n  description?: string;\n}\n","import type { ApiSpec, Service, Operation, HttpMethod, PaginationEndOfIteration, PaginationStrategy } from './types.js';\n\n/** Minimal snake_case converter for path segments (avoids cross-layer import). */\nfunction toSnake(s: string): string {\n  return s\n    .replace(/([a-z])([A-Z])/g, '$1_$2')\n    .replace(/[-\\s.]+/g, '_')\n    .toLowerCase();\n}\n\n/**\n * snake_case for a method name read from an `operationId` (`Operation.name`,\n * as the parser spelled it). The parser's camelCase keeps an acronym in\n * capitals (`getSSOAuthorizationUrl`, `createM2MApp`, `createJWTToken`), and\n * an `operationIdTransform` can hand the id back as written (`list-pets`,\n * `create_m2m_app`, `pets:adopt`), so a boundary is read wherever such a\n * name writes one, not only at the lower-to-upper step that is all `toSnake`\n * looks for in a path segment:\n *\n * - a lower-case letter before a capital (`createPet` → `create_pet`);\n * - a run of capitals before a capitalized word (`SSOAuthorization` →\n *   `sso_authorization`, `JWTToken` → `jwt_token`, `M2MApp` → `m2m_app`);\n * - a digit before a capitalized word (`V2Users` → `v2_users`); a digit\n *   otherwise stays in the word it was written in (`m2m`, `v2`, `oauth2`);\n * - any character that is not a letter or digit — `-`, `:`, `.`, `/`, a\n *   space, a bracket — is a separator, and a run of them is one.\n *\n * `OAuth`, which the parser's camelCase spells so and the acronym rule would\n * read as `o_auth`, is put back together (`getOAuth2Token` → `get_oauth2_token`).\n */\nexport function snakeCaseOperationName(name: string): string {\n  const words = name\n    .replace(/[^a-zA-Z0-9]+/g, '_')\n    .replace(/([a-z])([A-Z])/g, '$1_$2')\n    .replace(/([0-9])([A-Z][a-z])/g, '$1_$2')\n    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n    .toLowerCase()\n    .split('_')\n    .filter((word) => word.length > 0);\n  const joined: string[] = [];\n  for (const word of words) {\n    if (joined[joined.length - 1] === 'o' && /^auth\\d*$/.test(word)) {\n      joined[joined.length - 1] = `o${word}`;\n    } else {\n      joined.push(word);\n    }\n  }\n  return joined.join('_');\n}\n\n/** One segment of a path template as readPath reads it. */\nexport interface PathSegment {\n  /** A `{param}`, a literal, or the verb of a custom method. */\n  text: string;\n  /** `true` for a verb written after a colon: `adopt` in `/pets/{petId}:adopt`. */\n  customMethod: boolean;\n}\n\n/**\n * The segments of a path template, with a custom method split off the\n * segment it is written on. An API in the Google AIP-136 style appends an\n * action to a resource or collection after a colon, so `/pets/{petId}:adopt`\n * and `/pets:batchGet` each end in one URL segment that names both a thing\n * and a verb. Every name read from a path goes through this function (or\n * pathSegments, its text alone) and sees such a segment as the two it stands\n * for — `{petId}` then `adopt`, `pets` then `batchGet` — so a custom method\n * is named like the same action written with a slash (`/pets/{petId}/adopt`,\n * `/pets/batchGet`), and the verb never lands inside a parameter word. The\n * verb is marked `customMethod` for the two readings that treat it apart\n * from a slash-written literal: it never names a service, and it counts\n * against a path's plainness when inline model names collide (see the\n * parser's serviceSegmentIndex and pathDeviation). A colon inside a\n * parameter's braces, wherever they sit in the segment, is part of its name\n * and does not split it: `file-{file_path:path}` is one segment. AIP-136\n * appends a single verb, so a custom method starts only at a segment's one\n * colon outside braces: a segment with several, such as the literal\n * `urn:pet:1`, is kept whole, and is a literal even when a parameter opens\n * it (see isParameterSegment).\n * Empty segments — a leading, trailing or doubled slash, or an empty side of\n * a colon — are dropped. The operation's `path` itself is never rewritten: it\n * is the URL the SDK requests.\n */\nexport function readPath(path: string): PathSegment[] {\n  const segments: PathSegment[] = [];\n  for (const segment of path.split('/')) {\n    const outside = blankBracedColons(segment);\n    const colon = outside.indexOf(':');\n    const single = colon !== -1 && colon === outside.lastIndexOf(':');\n    const parts = single ? [segment.slice(0, colon), segment.slice(colon + 1)] : [segment];\n    parts.forEach((part, i) => {\n      if (part) segments.push({ text: part, customMethod: i > 0 });\n    });\n  }\n  return segments;\n}\n\n/** The text of each segment readPath reads: `/pets/{petId}:adopt` → `pets`, `{petId}`, `adopt`. */\nexport function pathSegments(path: string): string[] {\n  return readPath(path).map((segment) => segment.text);\n}\n\n/**\n * Whether a segment readPath reads is a path parameter: it starts with a\n * parameter's braces (`{petId}`, `{pet:id}`, `{tag}.json`) and has no colon\n * outside braces. A segment readPath keeps whole for its several colons is\n * one literal even when a parameter opens it, as `urn:pet:1` is, so the\n * parser reads `{petId}:adopt:now` as a literal and its words reach the\n * names read from it, instead of a parameter whose tail drops out.\n */\nexport function isParameterSegment(segment: string): boolean {\n  return segment.startsWith('{') && !blankBracedColons(segment).includes(':');\n}\n\n/** A segment with the colons inside its braces blanked out, every index kept in place. */\nfunction blankBracedColons(segment: string): string {\n  return segment.replace(/\\{[^}]*\\}/g, (param) => param.replaceAll(':', ' '));\n}\n\n// ---------------------------------------------------------------------------\n// Hint types — consumer-provided overrides for operation resolution\n// ---------------------------------------------------------------------------\n\n/** Per-operation override keyed by \"METHOD /path\" (e.g. \"POST /auth/token\"). */\nexport interface OperationHint {\n  /** Override the algorithm-derived method name. */\n  name?: string;\n  /** Remount this operation to a different service/namespace (PascalCase). */\n  mountOn?: string;\n  /** Split a union-body operation into N typed wrapper methods. */\n  split?: SplitHint[];\n  /** Inject constant body defaults (e.g. { grant_type: 'password' }). */\n  defaults?: Record<string, string | number | boolean>;\n  /** Fields the SDK reads from client config at runtime (e.g. ['client_id']). */\n  inferFromClient?: string[];\n  /**\n   * Marks this operation as a URL builder rather than a real HTTP call. Emitters\n   * should generate a method that returns the constructed URL (typically as a\n   * string) without performing any I/O. Used for OAuth-style redirect endpoints\n   * such as /auth/authorize and /accounts/sessions/logout.\n   */\n  urlBuilder?: boolean;\n  /**\n   * Explicit pagination for this operation, applied by the parser (through\n   * `ParseOptions.operationHints`) rather than by `resolveOperations`. Same\n   * shape as the spec's `x-pagination` Operation Object extension; a field set\n   * here wins over the extension, which wins over name-based detection.\n   */\n  pagination?: PaginationHint;\n}\n\n/**\n * Explicit pagination for one operation — the object a spec can carry as\n * `x-pagination` on an Operation Object and that `OperationHint.pagination`\n * accepts from config. Every field is optional and layers over the\n * lower-precedence sources (config hint > `x-pagination` > detection), so\n * `{ strategy: 'page' }` alone keeps the detected `param` and `limitParam`.\n *\n * `strategy: 'none'` turns pagination off for the operation; a list envelope\n * is then kept as a plain response model rather than unwrapped. Any other\n * strategy needs a `param`, from some source, that names one of the\n * operation's query parameters. An override that fails validation — unknown\n * strategy, missing or undeclared parameter, one parameter as both `param`\n * and `limitParam`, a `pageStart` under a strategy other than `page`, a\n * `dataPath` that does not reach an array, an `endOfIteration` whose path\n * does not resolve in the primary response to a field of its kind's type,\n * malformed field — is reported with an `[oagen] Warning:` and ignored,\n * leaving the detected metadata as is.\n */\nexport interface PaginationHint {\n  strategy?: PaginationStrategy | 'none';\n  /** Query parameter that selects the page (cursor, offset, or page number). */\n  param?: string;\n  /** Query parameter that sets the page size; not the one `param` names. */\n  limitParam?: string;\n  /**\n   * First page number the API expects (`page` strategy only; set under\n   * another strategy, it makes the override unusable). Defaults to the page\n   * parameter's integer `default`, else its `minimum`, else 1.\n   */\n  pageStart?: number;\n  /**\n   * Dotted path to the data array inside the response. Resolved against the\n   * response, so the array's element type — not the wrapper — becomes\n   * `itemType`.\n   */\n  dataPath?: string;\n  /**\n   * Response field that ends the iteration. Its `path` must resolve in the\n   * primary response to a field whose type fits its `kind` — a boolean for\n   * `hasMore`, an integer or number for `totalPages` and `totalCount` — or\n   * the override is unusable.\n   */\n  endOfIteration?: PaginationEndOfIteration;\n}\n\nexport interface SplitHint {\n  /** Wrapper method name (snake_case). */\n  name: string;\n  /** The discriminated union variant model name (e.g. 'PasswordSessionAuthenticateRequest'). */\n  targetVariant: string;\n  /** Constant body fields injected by the wrapper. */\n  defaults?: Record<string, string | number | boolean>;\n  /** Fields the SDK reads from client config at runtime. */\n  inferFromClient?: string[];\n  /** Only these body fields are exposed as method params. If omitted, all non-default/non-inferred fields are exposed. */\n  exposedParams?: string[];\n  /**\n   * Subset of exposedParams that should be emitted as optional even when the\n   * variant model would otherwise mark them required (or when the variant has\n   * no addressable model, as happens for inline oneOf branches).\n   */\n  optionalParams?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Resolved output — consumed by emitters\n// ---------------------------------------------------------------------------\n\nexport interface ResolvedOperation {\n  /** The original IR operation (preserves description, params, types, etc.). */\n  operation: Operation;\n  /** The original IR service that owns this operation. */\n  service: Service;\n  /** Resolved snake_case method name (emitters convert to their convention). */\n  methodName: string;\n  /** Resolved target service/namespace (PascalCase). */\n  mountOn: string;\n  /** For split operations: one wrapper per union variant. */\n  wrappers?: ResolvedWrapper[];\n  /** Constant defaults injected into query/body at runtime (from operation-level hint). */\n  defaults: Record<string, string | number | boolean>;\n  /** Fields the SDK reads from client config at runtime (from operation-level hint). */\n  inferFromClient: string[];\n  /** Marks this operation as a URL builder; emitters should not generate an HTTP call. */\n  urlBuilder: boolean;\n}\n\nexport interface ResolvedWrapper {\n  /** Wrapper method name (snake_case). */\n  name: string;\n  /** The discriminated union variant model name. */\n  targetVariant: string;\n  /** Constant body defaults injected by the wrapper. */\n  defaults: Record<string, string | number | boolean>;\n  /** Fields read from client config at runtime. */\n  inferFromClient: string[];\n  /** Body fields exposed as method params. */\n  exposedParams: string[];\n  /** Optional body fields (not required in the variant). */\n  optionalParams: string[];\n  /** Response model name (if any). */\n  responseModelName: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Algorithm\n// ---------------------------------------------------------------------------\n\n/**\n * Action verbs recognised at the terminal path segment.\n * When a path ends with one of these, we use it as the verb instead of\n * deriving a CRUD verb from the HTTP method.\n */\nconst ACTION_VERBS = new Set([\n  'accept',\n  'activate',\n  'authorize',\n  'challenge',\n  'check',\n  'complete',\n  'confirm',\n  'deactivate',\n  'disable',\n  'enable',\n  'enroll',\n  'generate',\n  'reactivate',\n  'resend',\n  'revoke',\n  'send',\n  'verify',\n]);\n\n/** Map HTTP method → default CRUD verb. */\nconst CRUD_VERB: Record<HttpMethod, string> = {\n  get: 'list',\n  post: 'create',\n  put: 'update',\n  patch: 'update',\n  delete: 'delete',\n  head: 'get',\n  options: 'list',\n  trace: 'list',\n};\n\n/**\n * Naive singularization: strips trailing \"s\" with common-sense exceptions.\n * Good enough for API resource nouns; not a general-purpose English stemmer.\n */\nfunction singularize(word: string): string {\n  if (word.length <= 2) return word;\n  if (word.endsWith('ies')) return word.slice(0, -3) + 'y';\n  if (\n    word.endsWith('ses') ||\n    word.endsWith('zes') ||\n    word.endsWith('xes') ||\n    word.endsWith('ches') ||\n    word.endsWith('shes')\n  ) {\n    return word.slice(0, -2);\n  }\n  if (word.endsWith('ss') || word.endsWith('us') || word.endsWith('is')) return word;\n  if (word.endsWith('s')) return word.slice(0, -1);\n  return word;\n}\n\n/**\n * Derive a snake_case method name from an operation's HTTP method and path.\n *\n * Rules:\n * 1. Strip path-param segments (`{id}`, `{slug}`, etc.); a custom method\n *    written after a colon (`{id}:verify`, `factors:enroll`) is read as its\n *    segment followed by the verb (see pathSegments), so it is named like\n *    `{id}/verify` and `factors/enroll`, and a segment kept whole for its\n *    several colons is a literal (see isParameterSegment), even one braces\n *    open and close (`{id}:a:b{ext}`)\n * 2. If the terminal segment is an action verb, use it as the verb\n * 3. Otherwise, use the CRUD verb for the HTTP method\n * 4. For GET on a collection (no trailing {id}), use \"list\"; with {id}, use \"get\"\n * 5. For POST on a resource path, if only one path param, use \"create\" singular\n * 6. Singularize the resource noun for single-resource operations\n */\nexport function deriveMethodName(op: Operation, _service: Service): string {\n  const segments = pathSegments(op.path);\n\n  // Separate static segments from param segments\n  const staticSegments: string[] = [];\n  let trailingParam = false;\n  for (const seg of segments) {\n    if (isParameterSegment(seg) && seg.endsWith('}')) {\n      trailingParam = true;\n    } else {\n      staticSegments.push(seg);\n      trailingParam = false;\n    }\n  }\n\n  if (staticSegments.length === 0) {\n    return `${CRUD_VERB[op.httpMethod] ?? 'get'}_root`;\n  }\n\n  const terminal = toSnake(staticSegments[staticSegments.length - 1]);\n\n  // Check if terminal is an action verb\n  if (ACTION_VERBS.has(terminal)) {\n    // Resource context from preceding segments\n    const context = staticSegments.slice(0, -1).filter((s) => !isParameterSegment(s));\n    const resource = context.length > 0 ? toSnake(singularize(context[context.length - 1])) : '';\n    if (resource) {\n      return `${terminal}_${resource}`;\n    }\n    return terminal;\n  }\n\n  // Determine verb from HTTP method\n  let verb = CRUD_VERB[op.httpMethod] ?? 'get';\n\n  // GET with trailing {id} → \"get\" instead of \"list\"\n  if (op.httpMethod === 'get' && trailingParam) {\n    verb = 'get';\n  }\n\n  // Build resource name from static segments.\n  // When path params separate static segments, include the penultimate static\n  // segment (singularized) as a parent-context prefix to disambiguate nested paths.\n  // e.g. /projects/{id}/roles → \"project_roles\"\n  let resource = toSnake(terminal);\n  if (staticSegments.length >= 2) {\n    const penultimate = staticSegments[staticSegments.length - 2];\n    // Check if a path param appears between the penultimate and terminal segments\n    // in the original path by finding both positions and looking for {…} between them.\n    const penIdx = segments.lastIndexOf(penultimate);\n    const termIdx = segments.lastIndexOf(staticSegments[staticSegments.length - 1]);\n    const hasParamBetween = segments.slice(penIdx + 1, termIdx).some((s) => s.startsWith('{'));\n    if (hasParamBetween) {\n      const prefix = toSnake(singularize(penultimate));\n      resource = `${prefix}_${resource}`;\n    }\n  }\n\n  // Singularize when:\n  //   * there's a trailing path param (single-resource read/update/delete), or\n  //   * the verb itself implies a single-resource operation (e.g. POST → create\n  //     always creates one item even when posted to a collection endpoint).\n  const isSingleResource = trailingParam || verb === 'create';\n  const noun = isSingleResource ? singularize(resource) : resource;\n\n  // For \"list\" verb, keep plural\n  const finalNoun = verb === 'list' ? resource : noun;\n\n  return `${verb}_${finalNoun}`;\n}\n\n/**\n * Resolve a service name to its mount target.\n *\n * Rule keys are either exact service names or trailing-`*` prefix patterns\n * (e.g. `UserManagement*`). Precedence:\n *\n *   1. An exact key always wins.\n *   2. Otherwise the wildcard with the longest prefix wins, so\n *      `UserManagementOrganizationMembership*` beats `UserManagement*`.\n *\n * Matching is plain string comparison (`startsWith`) — `*` is only recognised\n * as the final character and no regex is ever built from rule keys.\n *\n * @param name - The IR service name to resolve.\n * @param mounts - Exact-name or trailing-`*` pattern → target service mappings.\n * @returns The mount target, or `name` unchanged when no rule matches.\n */\nexport function resolveMountTarget(name: string, mounts: Record<string, string>): string {\n  const exact = mounts[name];\n  if (exact !== undefined) return exact;\n\n  let best: string | undefined;\n  let bestLen = -1;\n  for (const [pattern, target] of Object.entries(mounts)) {\n    if (!pattern.endsWith('*')) continue;\n    const prefix = pattern.slice(0, -1);\n    if (name.startsWith(prefix) && prefix.length > bestLen) {\n      best = target;\n      bestLen = prefix.length;\n    }\n  }\n  return best ?? name;\n}\n\n/**\n * Where a method name comes from when no `name` hint sets it: `path` derives\n * it from the HTTP method and path (`deriveMethodName`); `operationId` takes\n * the operation's own name when the document declares an `operationId`\n * (`Operation.name`, as the parser spelled it, in snake_case — see\n * {@link snakeCaseOperationName} for where the word boundaries are read) and\n * derives it from the path only for a path-named operation.\n */\nexport type OperationNaming = 'path' | 'operationId';\n\n/**\n * The settings {@link resolveOperations} resolves a spec's operations with —\n * the config's `operationHints`, `mountRules` and `operationNaming` — which\n * together decide the class (`mountOn`) and the method (`methodName`) that\n * `generate` writes each operation as. Every command that reads the SDK\n * `generate` writes resolves with the same settings: `compat-extract` matches\n * the SDK's callables by the names they resolve to, and `verify`'s compat\n * scope and staleness check read the classes and methods they resolve to\n * (see `specDerivedNames`, `specDerivedMethodPaths` and `detectStaleSymbols`\n * in `compat`). Under `mountRules: { Pets: 'Animals' }` and\n * `operationHints: { 'GET /pets': { name: 'list_all' } }`, `GET /pets` and\n * `GET /pets/{id}` tagged `Pets` resolve to `Animals.list_all` and\n * `Animals.get_pet`; with no settings, to `Pets.list_pets` and `Pets.get_pet`.\n */\nexport interface OperationResolution {\n  operationHints?: Record<string, OperationHint>;\n  mountRules?: Record<string, string>;\n  operationNaming?: OperationNaming;\n}\n\n/**\n * Resolve all operations in the spec, applying hints and mount rules.\n *\n * @param spec - The parsed API spec\n * @param hints - Per-operation overrides keyed by \"METHOD /path\"\n * @param mountRules - Service name → target service mappings; keys may be\n *   exact names or trailing-`*` prefix patterns (see {@link resolveMountTarget})\n * @param operationNaming - Where an unhinted method name comes from; `path`\n *   unless the consumer asks for `operationId` (see {@link OperationNaming})\n * @returns Resolved operations ready for emitter consumption\n */\nexport function resolveOperations(\n  spec: ApiSpec,\n  hints?: Record<string, OperationHint>,\n  mountRules?: Record<string, string>,\n  operationNaming: OperationNaming = 'path',\n): ResolvedOperation[] {\n  const resolved: ResolvedOperation[] = [];\n  const hintMap = hints ?? {};\n  const mounts = mountRules ?? {};\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      const key = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const hint = hintMap[key];\n\n      // Resolve method name: hint > algorithm, or — when the consumer asked\n      // for `operationId` naming — hint > operationId > algorithm. An operation\n      // the document named then keeps that name (as the parser spelled it, so\n      // an operationIdTransform is honoured), snake_cased word by word (the\n      // parser's camelCase writes acronyms in capitals, and a transform may\n      // keep the id's own separators); only a path-named operation gets a\n      // name derived from its method and path.\n      const fromOperationId = operationNaming === 'operationId' && op.operationId !== undefined;\n      const methodName =\n        hint?.name ?? (fromOperationId ? snakeCaseOperationName(op.name) : deriveMethodName(op, service));\n\n      // Resolve mount target: per-op hint > service mount rule > original service\n      const mountOn = hint?.mountOn ?? resolveMountTarget(service.name, mounts);\n\n      // Build wrappers for split operations\n      let wrappers: ResolvedWrapper[] | undefined;\n      if (hint?.split) {\n        wrappers = hint.split.map((sh) => ({\n          name: sh.name,\n          targetVariant: sh.targetVariant,\n          defaults: sh.defaults ?? {},\n          inferFromClient: sh.inferFromClient ?? [],\n          exposedParams: sh.exposedParams ?? [],\n          optionalParams: sh.optionalParams ?? [],\n          responseModelName: resolveResponseModelName(op),\n        }));\n      }\n\n      resolved.push({\n        operation: op,\n        service,\n        methodName,\n        mountOn,\n        wrappers,\n        defaults: hint?.defaults ?? {},\n        inferFromClient: hint?.inferFromClient ?? [],\n        urlBuilder: hint?.urlBuilder ?? false,\n      });\n    }\n  }\n\n  return resolved;\n}\n\n/** Extract the response model name from an operation (for wrapper metadata). */\nfunction resolveResponseModelName(op: Operation): string | null {\n  if (op.httpMethod === 'delete') return null;\n  const ref = op.response;\n  if (ref.kind === 'model') return ref.name;\n  if (ref.kind === 'nullable' && ref.inner.kind === 'model') return ref.inner.name;\n  return null;\n}\n\n/** One pair of distinct paths that resolved to the same `mountOn.methodName`. */\nexport interface ResolvedMethodCollision {\n  /** The shared `Service.method_name` key both paths resolved to. */\n  key: string;\n  first: { httpMethod: string; path: string };\n  second: { httpMethod: string; path: string };\n}\n\n/**\n * Find every pair of distinct paths that resolve to the same SDK method name.\n *\n * Emitters already refuse to generate on a collision, but they only run inside\n * the per-language build matrix — so a spec addition that collides fails every\n * matrix job minutes in, with no cheap way to catch it first. Surfacing the same\n * check from `oagen resolve` turns that into a seconds-long precheck.\n *\n * Returns every collision rather than throwing on the first, so a spec that\n * introduces several is fixed in one pass instead of one CI round-trip each.\n *\n * Callers that generate a subset of services must filter to the operations they\n * will actually emit before calling this: a collision between two out-of-scope\n * paths is not that run's problem.\n */\nexport function findResolvedMethodCollisions(resolved: ResolvedOperation[]): ResolvedMethodCollision[] {\n  const seen = new Map<string, { httpMethod: string; path: string }>();\n  const collisions: ResolvedMethodCollision[] = [];\n\n  for (const r of resolved) {\n    const key = `${r.mountOn}.${r.methodName}`;\n    const current = { httpMethod: r.operation.httpMethod.toUpperCase(), path: r.operation.path };\n    const existing = seen.get(key);\n\n    // The same path AND method twice is one operation seen through two\n    // services, not a collision. Both have to match: two *different* methods\n    // on one path (`GET /x` and `POST /x` hinted to the same name) are\n    // distinct operations competing for a single SDK method, and a path-only\n    // comparison accepts them silently.\n    if (existing && (existing.path !== current.path || existing.httpMethod !== current.httpMethod)) {\n      collisions.push({ key, first: existing, second: current });\n      continue;\n    }\n    if (!existing) seen.set(key, current);\n  }\n\n  return collisions;\n}\n","/**\n * Structured error hierarchy for oagen.\n *\n * Every error carries a human-readable `hint` that suggests a recovery action.\n * The hint is appended to the `message` so it appears in stack traces and logs.\n */\n\n/** Base class for all oagen errors. */\nexport class OagenError extends Error {\n  readonly hint: string;\n\n  constructor(message: string, hint: string) {\n    const fullMessage = hint ? `${message}\\nHint: ${hint}` : message;\n    super(fullMessage);\n    this.name = 'OagenError';\n    this.hint = hint;\n  }\n}\n\n/** Thrown when a command should terminate with a specific exit code. */\nexport class CommandError extends OagenError {\n  readonly exitCode: number;\n\n  constructor(message: string, hint: string, exitCode: number) {\n    super(message, hint);\n    this.name = 'CommandError';\n    this.exitCode = exitCode;\n  }\n}\n\n/** Thrown when an OpenAPI spec cannot be parsed or has an unsupported version. */\nexport class SpecParseError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'SpecParseError';\n  }\n}\n\n/** Thrown when configuration files (manifests, API surfaces, overlays) are missing or malformed. */\nexport class ConfigError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ConfigError';\n  }\n}\n\n/** Thrown when a config file exists but cannot be loaded or evaluated. */\nexport class ConfigLoadError extends ConfigError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ConfigLoadError';\n  }\n}\n\n/** Thrown when a config targets a different IR version than the installed package. */\nexport class ConfigVersionMismatchError extends ConfigError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ConfigVersionMismatchError';\n  }\n}\n\n/** Thrown when an API surface extractor encounters a problem. */\nexport class ExtractorError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ExtractorError';\n  }\n}\n\n/** Thrown when a requested language or extractor is not found in a registry. */\nexport class RegistryError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'RegistryError';\n  }\n}\n\n/** Thrown for internal invariant violations that indicate a bug. */\nexport class InternalError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'InternalError';\n  }\n}\n","/**\n * Known compound tokens that the regex-based splitter over-splits.\n * Each entry is [lowercase-word-sequence, canonical-form].\n * Sorted longest-first so greedy matching works correctly.\n */\nconst COMPOUND_WORDS: [string[], string][] = [\n  [['m', '2', 'm'], 'M2M'],\n  [['o', 'auth'], 'OAuth'],\n];\n\n/**\n * Recombine adjacent words that form a known compound token.\n */\nfunction recombineCompounds(words: string[]): string[] {\n  const result: string[] = [];\n  let i = 0;\n  while (i < words.length) {\n    let matched = false;\n    for (const [pattern, canonical] of COMPOUND_WORDS) {\n      if (i + pattern.length <= words.length) {\n        const matches = pattern.every((p, j) => words[i + j].toLowerCase() === p);\n        if (matches) {\n          result.push(canonical);\n          i += pattern.length;\n          matched = true;\n          break;\n        }\n      }\n    }\n    if (!matched) {\n      result.push(words[i]);\n      i++;\n    }\n  }\n  return result;\n}\n\n/**\n * Split a string into words, handling:\n * - camelCase / PascalCase boundaries\n * - snake_case / kebab-case separators\n * - Consecutive capitals (e.g., \"HTTPClient\" → [\"HTTP\", \"Client\"])\n * - Numbers as word boundaries (e.g., \"OAuth2Token\" → [\"OAuth\", \"2\", \"Token\"])\n * - Known compounds are recombined (e.g., \"M2M\" stays as one word)\n */\nexport function splitWords(s: string): string[] {\n  if (!s) return [];\n\n  const words = s\n    .replace(/[^a-zA-Z0-9_\\-\\s.]/g, '_') // replace non-alphanumeric chars with separator\n    .replace(/([a-z])([A-Z])/g, '$1\\0$2') // camelCase boundary\n    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1\\0$2') // consecutive caps boundary\n    .replace(/([a-zA-Z])(\\d)/g, '$1\\0$2') // letter to number\n    .replace(/(\\d)([a-zA-Z])/g, '$1\\0$2') // number to letter\n    .split(/[\\0_\\-\\s.]+/)\n    .filter((w) => w.length > 0);\n\n  return recombineCompounds(words);\n}\n\nexport const ACRONYM_SET = new Set(['SSO', 'FGA', 'SAML', 'SCIM', 'JWT', 'HMAC', 'M2M']);\n\nexport function toPascalCase(s: string, acronyms?: Set<string>): string {\n  const merged = acronyms ? new Set([...ACRONYM_SET, ...acronyms]) : ACRONYM_SET;\n  return splitWords(s)\n    .map((w) => {\n      const upper = w.toUpperCase();\n      if (merged.has(upper)) return upper;\n      // Special case: OAuth should stay as OAuth, not OAUTH\n      if (upper === 'OAUTH') return 'OAuth';\n      return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();\n    })\n    .join('');\n}\n\nexport function toCamelCase(s: string, acronyms?: Set<string>): string {\n  const merged = acronyms ? new Set([...ACRONYM_SET, ...acronyms]) : ACRONYM_SET;\n  const words = splitWords(s);\n  if (words.length === 0) return '';\n  return words\n    .map((w, i) => {\n      if (i === 0) return w.toLowerCase();\n      const upper = w.toUpperCase();\n      if (merged.has(upper)) return upper;\n      if (upper === 'OAUTH') return 'OAuth';\n      return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();\n    })\n    .join('');\n}\n\nexport function toSnakeCase(s: string): string {\n  return splitWords(s)\n    .map((w) => w.toLowerCase())\n    .join('_');\n}\n\nexport function toKebabCase(s: string): string {\n  return splitWords(s)\n    .map((w) => w.toLowerCase())\n    .join('-');\n}\n\nexport function toUpperSnakeCase(s: string): string {\n  return splitWords(s)\n    .map((w) => w.toUpperCase())\n    .join('_');\n}\n\n/**\n * `name` with the numeric suffix `n`, the one spelling of every numbered\n * operation, model and enum name: `list` + 2 is `list2`. A name that already\n * ends in a digit takes the number behind `No`, so that it cannot be read as\n * part of the number the name ends with: `listV1` + 2 is `listV1No2`, never\n * `listV12`, which reads as version 12 of the API, and `PetSizeV2` + 2 is\n * `PetSizeV2No2`. The hex hash that sets a path-derived or webhook stem\n * apart is appended the same way, so one that starts with a digit is set off\n * too (`PetsTop10` + `567B59` is `PetsTop10No567B59`, never\n * `PetsTop10567B59`) and one that starts with a letter follows the name as\n * it is (`PetsTop10Ba41B5`). An underscore would not do: splitWords reads a\n * digit run as a word of its own, so `listV1_2` re-cased by toPascalCase or\n * toCamelCase is `ListV12` or `listV12` again. The name is read as given, so\n * a caller numbers a name in its final spelling; one that is cased only\n * later is numbered by numberedProperty.\n */\nexport function numberedName(name: string, n: number | string): string {\n  const suffix = String(n);\n  return /\\d$/.test(name) && /^\\d/.test(suffix) ? `${name}No${suffix}` : `${name}${suffix}`;\n}\n\n/**\n * `property` with the numeric suffix `n`, for a property name that is cased\n * only later: the raw parameter or header name the shape registry and a\n * webhook's `mintParameter` extract a schema under, which toPascalCase turns\n * into the model name. The number is spelled as numberedName spells it on the\n * cased name, so one that ends in a digit once the characters that are\n * neither letters nor digits are dropped (`filter[v2]`, `x-meta-v2_`,\n * `filter_v2_`) takes it behind `No` too: `filter[v2]` + 2 is\n * `filter[v2]No2`, cased `FilterV2No2`, never `filter[v2]2`, which cases to\n * `FilterV22` and reads as version 22 (#533); `query_payload` + 2 is still\n * `query_payload2`. The property is returned as written, not cased: the\n * stems a site's siblings settled on are compared as strings, and\n * toPascalCase is not idempotent (`sso_v2` is `SSOV2`, re-cased `Ssov2`).\n */\nexport function numberedProperty(property: string, n: number | string): string {\n  const cased = toPascalCase(property);\n  return `${property}${numberedName(cased, n).slice(cased.length)}`;\n}\n\nconst BACKEND_SUFFIXES = ['Controller'];\n\nexport function stripBackendSuffixes(name: string): string {\n  for (const suffix of BACKEND_SUFFIXES) {\n    if (name.endsWith(suffix) && name.length > suffix.length) {\n      return name.slice(0, -suffix.length);\n    }\n  }\n  return name;\n}\n\nexport function stripBackendPrefixes(name: string): string {\n  return name.replace(/Userland/g, '').replace(/Controller/g, '');\n}\n\n/**\n * Remove ListItem / ByExternalId / ByResourceId / ForResource markers from PascalCase names.\n * E.g. \"DirectoriesListItemState\" → \"DirectoriesState\"\n */\nexport function stripListItemMarkers(name: string): string {\n  return name\n    .replace(/ListItem/g, '')\n    .replace(/ByExternalId/g, '')\n    .replace(/ByResourceId/g, '')\n    .replace(/ForResource/g, '');\n}\n\n/** Words that look plural but must NOT be singularized. */\nconst SINGULAR_SAFE_LIST = new Set([\n  'Status',\n  'Address',\n  'Access',\n  'Process',\n  'Progress',\n  'Success',\n  'Radius',\n  'Canvas',\n  'Alias',\n  'Basis',\n  'Bus',\n  'Species',\n  'Series',\n]);\n\n/**\n * The singular of a word read as a plural, by suffix alone: `word` ends in\n * `s`, and the caller has ruled out whatever it does not read as a plural.\n * The one set of rules `singularize` and `singularizePathSegment` share, so a\n * field, a component and a path segment spell one noun's singular the same\n * way (`causes` is `cause` as an array field and as a resource; #620):\n * - `-ies` → `-y` when the word is longer than four letters (`directories` →\n *   `directory`; a short `-ies` word keeps its `ie`, `pies` → `pie`);\n * - `-yses` → `-ysis` (`analyses` → `analysis`);\n * - the `es` of a sibilant stem is dropped — `-sses`, `-uses` after a\n *   consonant, `-iases`, `-xes`, `-ches`, `-shes` (`addresses` → `address`,\n *   `statuses` → `status`, `aliases` → `alias`, `boxes` → `box`, `batches` →\n *   `batch`, `hashes` → `hash`) — except `-aches` after a consonant, which\n *   is an `-ache` noun's plain `s` (`caches` → `cache`, `headaches` →\n *   `headache`, `mustaches` → `mustache`; an `-ach` noun has a vowel before\n *   the `a`, `coaches` → `coach`, `beaches` → `beach`);\n * - any other `s` is a plain plural `s` (`notes` → `note`, `causes` →\n *   `cause`, `licenses` → `license`, `responses` → `response`, `releases` →\n *   `release`, `warehouses` → `warehouse`).\n * Case is preserved — the rules only slice, except the `y` and `is` they\n * write, which take the case of the letters they replace (`DIRECTORIES` →\n * `DIRECTORY`, `ANALYSES` → `ANALYSIS`).\n */\nfunction stripPluralSuffix(word: string): string {\n  const lower = word.toLowerCase();\n  // `directories` → `directory`; a short `-ies` word keeps its `ie` (`pies` → `pie`).\n  if (lower.endsWith('ies') && lower.length > 4) {\n    return word.slice(0, -3) + (word.endsWith('IES') ? 'Y' : 'y');\n  }\n  // `analyses` → `analysis`: every English `-yses` noun is the plural of a\n  // `-ysis` noun (`paralyses`, `dialyses`, `catalyses`).\n  if (lower.endsWith('yses')) return word.slice(0, -2) + (word.endsWith('ES') ? 'IS' : 'is');\n  // An `es` added to a sibilant stem: `addresses`, `statuses`, `aliases`,\n  // `boxes`, `batches`, `hashes`. A vowel before `uses` is a plain `s` instead\n  // (`warehouses`), and so is any letter but `i` before `ases` (`cases`,\n  // `releases`): no English noun ends in `-iase`, so `aliases` and `biases`\n  // are `-ias` nouns.\n  if (lower.endsWith('sses') || /[^aeiou]uses$/.test(lower) || lower.endsWith('iases')) return word.slice(0, -2);\n  // An `-ache` noun (`caches`, `headaches`, `mustaches`) is the `-aches` word\n  // with a consonant before the `a`; an `-ach` noun has a vowel there\n  // (`coaches`, `beaches`, `approaches`) and drops its `es` below.\n  if (/[^aeiou]aches$/.test(lower)) return word.slice(0, -1);\n  if (lower.endsWith('xes') || lower.endsWith('ches') || lower.endsWith('shes')) return word.slice(0, -2);\n  return word.slice(0, -1);\n}\n\n/**\n * Conservative singularize for one word of a model name — the leading word\n * of a component name (`cleanSchemaName`), the trailing word of an inline\n * model's name (`qualifyInlineModelName`), the field a nested error body's\n * items are reached through (`collapseErrorBodies`), the array a `dataPath`\n * hint ends in (`inlineItemNameForPath`) — or a raw field name. The suffix\n * rules are the ones a path segment is singularized by (`stripPluralSuffix`,\n * shared with `singularizePathSegment`), so a field and a resource of one\n * noun spell its singular alike: `Directories` → `Directory`, `Organizations`\n * → `Organization`, `Statuses` → `Status`, `Addresses` → `Address`, `Boxes`\n * → `Box`, `Batches` → `Batch`, `Causes` → `Cause`, `Licenses` → `License`,\n * `Responses` → `Response`, `Analyses` → `Analysis`, `Caches` → `Cache`\n * (#620; before it, every `-ses` word lost its `es` — `Caus`, `Licens`,\n * `Respons` — and every other `-es` word only its `s` — `Boxe`, `Batche`).\n * What is read as a plural at all is decided here, not by the path\n * segment's guards: a safe-listed word (`Status`, `Address`, `Series`, …)\n * and its `-es` plural (`Canvases` → `Canvas`, `Radiuses` → `Radius`,\n * whatever the suffix rules would make of them), a word of four letters or\n * fewer (`Pets`, `Tags`, `Bus`, `Gas`, `News`, `Axes` are kept as they are,\n * since a short word is as likely a singular) and a word ending in `ss`\n * (`Class`) are never singularized, and neither is a `-ysis` word, the\n * singular the `-yses` rule writes (`Analysis`); any other `-us` or `-is`\n * word is read as a plural, as it always was (`Menus` → `Menu`, `Emojis` →\n * `Emoji`, at the price of `Campus` → `Campu`). The suffix rules' limits\n * are the ones documented on `singularizePathSegment`, and reach a model\n * name as they reach an operation's: `Gases` → `Gase`, `Lenses` → `Lense`,\n * `Atlases` → `Atlase`, `Niches` → `Nich`, `Diagnoses` → `Diagnose` (where\n * the two-branch rule before #620 happened to give `Gas`, `Lens`, `Atlas`\n * and `Niche`). Every singular the `-ies`, `-yses` and sibilant rules write\n * is returned as it is when passed back in, so `cleanSchemaName` is\n * idempotent on it; the `-us` a consonant + `-uses` plural gives is not,\n * since a `-us` word is read as a plural (`Bonuses` → `Bonus` → `Bonu`,\n * `Campuses` → `Campus` → `Campu`, `Viruses` → `Virus` → `Viru`, as on\n * every version before this one).\n */\nexport function singularize(word: string): string {\n  if (SINGULAR_SAFE_LIST.has(word) || word.length <= 4) return word;\n  // `-ss` is never a plural (`Class`), and neither is `-ysis`, the singular\n  // the `-yses` rule writes (`Analysis`), so the singulars the suffix rules\n  // write are returned as they are when passed back in, as cleanSchemaName\n  // requires — all but the `-us` a consonant + `-uses` plural gives, which\n  // is read as a plural again (`Bonuses` → `Bonus` → `Bonu`).\n  if (!word.endsWith('s') || word.endsWith('ss') || word.endsWith('ysis')) return word;\n  // A safe-listed word's `-es` plural is that word (`Canvases` → `Canvas`,\n  // `Radiuses` → `Radius`), whatever the suffix rules would make of it.\n  if (word.endsWith('es') && SINGULAR_SAFE_LIST.has(word.slice(0, -2))) return word.slice(0, -2);\n  return stripPluralSuffix(word);\n}\n\n/**\n * Conservative singularisation of a path segment, for naming an operation on\n * one item of a collection: `pets` → `pet`, `api_keys` → `api_key`,\n * `directories` → `directory`, `addresses` → `address`, `statuses` → `status`,\n * `aliases` → `alias`, `analyses` → `analysis`, `boxes` → `box`, `batches` →\n * `batch`, `caches` → `cache`, `responses` → `response`.\n *\n * Suffix rules only (`stripPluralSuffix`, the rules `singularize` applies to\n * a model name's word, so `/causes/{id}` and a `causes` field spell one\n * `cause`), no dictionary, so anything that does not look plural is returned\n * as it is: a segment that does not end in `s`, or ends in `ss`, `us`, `is`\n * or `ias` (`status`, `analysis`, `alias`), or is an invariant plural\n * (`series`). Case is preserved — the rules only slice, except `-ies` → `-y`\n * and `-yses` → `-ysis`, whose `y` and `is` take the case of the letters they\n * replace (`DIRECTORIES` → `DIRECTORY`, `ANALYSES` → `ANALYSIS`, so splitWords\n * still sees one word) — and only the trailing word of a compound segment\n * matters. Idempotent: every singular it produces is returned as it is when\n * passed back in (`aliases` → `alias` → `alias`), so a comparison of two\n * words by their singular forms (see appendQualifier) is sound.\n *\n * Deliberately not handled — a resource that stems wrong should carry an\n * `operationId`: irregular plurals (`people`, `children`, `data`), `-ies`\n * words whose singular keeps the `ie` (`cookies` → `cooky`), `-oes` (`heroes`\n * → `heroe`), `-ches` nouns ending in `-che` other than a consonant + `-ache`\n * (`niches` → `nich`, `avalanches` → `avalanch`, `tranches` → `tranch`,\n * where `caches` → `cache` and `branches` → `branch` are the common\n * readings), `-uses`\n * nouns ending in `-use` (`excuses` → `excus`), `-zes` plurals of a doubled\n * `z` (`quizzes` → `quizze`, where `sizes` → `size` is the common reading),\n * `-ases` nouns ending in `-as`\n * other than `-ias` (`canvases` → `canvase`, where `cases` → `case` is the\n * common reading), `-es` plurals of `-is` nouns other than `-ysis` (`crises`\n * → `crise`, `theses` → `these`, where `premises` → `premise` and `cheeses`\n * → `cheese` are the common readings), singular nouns ending in `-as` other\n * than `-ias`, or in `-ns` (`canvas` → `canva`, `lens` → `len`, where `areas`\n * → `area` and `tokens` → `token` are the common readings), plurals of `-ia`\n * nouns (`utopias` is kept as it is, so that `alias` is), plurals of\n * `-u`/`-i` nouns (`menus`, `apis` are kept as they are) and acronyms (`sms`\n * → `sm`). These limits reach every segment the parser singularises — the\n * resource of an item operation, a deeper segment a path parameter follows\n * and the service noun a name restores — so `/messages/sms/{smsId}/attachments`\n * contributes `Sm` and `/design/canvas/{id}/layers/{layerId}` contributes\n * `Canva` to a qualified name.\n */\nexport function singularizePathSegment(segment: string): string {\n  const lower = segment.toLowerCase();\n  if (lower.length <= 2 || !lower.endsWith('s')) return segment;\n  if (lower.endsWith('series') || lower.endsWith('species') || lower.endsWith('news')) return segment;\n  // `-ias` is kept for `alias` and `bias`, the singulars the `-iases` rule\n  // below produces, at the price of the rarer `-ia` plurals (`utopias`).\n  if (lower.endsWith('ss') || lower.endsWith('us') || lower.endsWith('is') || lower.endsWith('ias')) return segment;\n  return stripPluralSuffix(segment);\n}\n\n/**\n * Compose all backend name cleaning transforms in order:\n * 1. Strip backend prefixes (Userland, Controller)\n * 2. Strip backend suffixes (Dto, DTO, Controller)\n * 3. Strip ListItem / ByExternalId markers\n * 4. Singularize leading resource word\n *\n * Must be idempotent: `cleanSchemaName(cleanSchemaName(x)) === cleanSchemaName(x)`\n * — which holds for every name but one whose leading word is a consonant +\n * `-uses` plural, since `singularize` reads the `-us` it writes as a plural\n * again (`Bonuses` → `Bonus` → `Bonu`; see singularize).\n */\n/** Strip `.js` extensions from import/export specifiers for dedup comparison. */\nexport function normalizeJsExtension(text: string): string {\n  return text.replace(/\\.js(['\"])/g, '$1');\n}\n\nexport function cleanSchemaName(name: string): string {\n  return singularizeLeadingWord(stripListItemMarkers(stripBackendPrefixes(stripBackendSuffixes(name))));\n}\n\n/**\n * `name` with its leading PascalCase word singularized (`NotesList` →\n * `NoteList`, `Pets` → `Pet`): the last step of cleanSchemaName, read on its\n * own where an id the cleaning only singularized must be told from one it\n * stripped a marker or a backend word from (resolveContestedOperationIdStems,\n * #627).\n */\nexport function singularizeLeadingWord(name: string): string {\n  const match = name.match(/^([A-Z][a-z]*)/);\n  if (!match) return name;\n  const leadWord = match[1];\n  const singular = singularize(leadWord);\n  return singular === leadWord ? name : singular + name.slice(leadWord.length);\n}\n","/**\n * Shared tree-sitter utilities.\n *\n * tree-sitter 0.21.x has a native binding bug: its internal UTF-16 buffer is\n * 32 768 uint16 units (32 768 characters for BMP text). When the JS input\n * callback returns a string >= 32 768 chars, `napi_get_value_string_utf16`\n * overflows and the C layer throws \"Invalid argument\". Work around this by\n * supplying a chunked callback for large sources instead of a raw string.\n */\n\nimport type Parser from 'tree-sitter';\n\nconst TS_SAFE_CHUNK = 32_767;\n\nexport function safeParse(parser: Parser, source: string): Parser.Tree {\n  if (source.length < TS_SAFE_CHUNK) {\n    return parser.parse(source);\n  }\n  return parser.parse((offset: number) => source.slice(offset, offset + TS_SAFE_CHUNK));\n}\n"],"mappings":";;;;;;;;;;AAgTA,SAAgB,gBACd,SACA,UACQ;CACR,OAAO,GAAG,QAAQ,aAAa,SAAS,KAAK,GAAG,SAAS,WAAW,GAAG,SAAS;AAClF;;;;;;;;;;;;;;AAq7CA,SAAgB,YAAY,GAAiB;CAE3C,MAAM,OAAQ,EAAc;CAC5B,MAAM,sBAAM,IAAI,MACd,4BAA4B,KAAK,mGACnC;CACA,IAAI,OAAO;CACX,MAAM;AACR;;;;;;;;AASA,SAAgB,mBAAmB,KAAuC;CACxE,QAAQ,IAAI,MAAZ;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,SACH,OAAO,IAAI;EACb,KAAK;EACL,KAAK;EACL,KAAK,YACH;CACJ;CACA,OAAO,YAAY,GAAG;AACxB;;;;;;;AAQA,SAAgB,YACd,KACA,SAMM;CACN,QAAQ,IAAI,MAAZ;EACE,KAAK;GACH,QAAQ,QAAQ,GAAG;GACnB;EACF,KAAK;GACH,QAAQ,OAAO,GAAG;GAClB;EACF,KAAK;GACH,YAAY,IAAI,OAAO,OAAO;GAC9B;EACF,KAAK;GACH,YAAY,IAAI,OAAO,OAAO;GAC9B;EACF,KAAK;GACH,KAAK,MAAM,KAAK,IAAI,UAAU,YAAY,GAAG,OAAO;GACpD;EACF,KAAK;GACH,IAAI,IAAI,SAAS,YAAY,IAAI,SAAS,OAAO;GACjD,YAAY,IAAI,WAAW,OAAO;GAClC;EACF,KAAK;GACH,QAAQ,UAAU,GAAG;GACrB;EACF,KAAK;GACH,QAAQ,YAAY,GAAG;GACvB;EACF,SACE,YAAY,GAAG;CACnB;AACF;;;;;;;AAQA,SAAgB,WACd,KACA,QAUG;CACH,QAAQ,IAAI,MAAZ;EACE,KAAK,aACH,OAAO,OAAO,UAAU,GAAG;EAC7B,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