{"version":3,"file":"diff-DRXLXJ3i.mjs","names":["extractDeclarationName","declarationKey","path","path","path","serializeDefault"],"sources":["../src/ir/server-url.ts","../src/ir/parameter-key.ts","../src/utils/media-type.ts","../src/engine/merge-adapters/url-fingerprint.ts","../src/engine/merge-adapters/dotnet.ts","../src/engine/merge-adapters/elixir.ts","../src/engine/merge-adapters/go.ts","../src/engine/merge-adapters/kotlin.ts","../src/engine/merge-adapters/node.ts","../src/engine/merge-adapters/php.ts","../src/engine/merge-adapters/python.ts","../src/engine/merge-adapters/ruby.ts","../src/engine/merge-adapters/rust.ts","../src/engine/merge-adapters/index.ts","../src/engine/merger.ts","../src/engine/json-merge.ts","../src/engine/writer.ts","../src/engine/scoped-services.ts","../src/engine/generate-files.ts","../src/engine/integrate.ts","../src/engine/formatter.ts","../src/engine/manifest.ts","../src/engine/orchestrator.ts","../src/engine/registry.ts","../src/differ/classify.ts","../src/differ/direction.ts","../src/differ/models.ts","../src/differ/security.ts","../src/differ/servers.ts","../src/differ/shapes.ts","../src/differ/media-types.ts","../src/differ/params.ts","../src/differ/operations.ts","../src/differ/services.ts","../src/differ/webhooks.ts","../src/differ/diff.ts"],"sourcesContent":["import type { ServerEntry, ServerVariable } from './types.js';\n\n/** Outcome of filling a server URL template with its variables' defaults. */\nexport interface ResolvedServerUrl {\n  /** The template with every placeholder that names a declared variable replaced by that variable's `default`. */\n  url: string;\n  /**\n   * Placeholder names still in `url` because the server declares no variable\n   * for them, in order of first appearance and without repeats.\n   */\n  unresolved: string[];\n}\n\n/**\n * Fill a server URL template with its variables' defaults.\n *\n * Each `{name}` is replaced by `variables[name].default`; a placeholder with no\n * declared variable is kept verbatim and reported in `unresolved`. The same\n * variable may appear more than once, and a declared variable the template\n * never mentions is simply unused (`serverUrlPlaceholders` lists the names the\n * template does mention). The substituted value is spliced in as text and not\n * scanned again, so a default such as `{other}` cannot trigger a second\n * substitution. A `{` with no closing `}`, an empty `{}`, and a `{` that opens\n * another `{` before closing are all literal text.\n *\n * Plain string scanning only: no pattern is built from the variable names, so\n * a name containing `.`, `+` or any other character is matched as written.\n *\n * The parser uses this for `ApiSpec.baseUrl`; an emitter that offers every\n * server (an environment picker, say) can resolve each `spec.servers[i]` the\n * same way instead of reading the OpenAPI document again.\n */\nexport function resolveServerUrl(server: Pick<ServerEntry, 'url' | 'variables'>): ResolvedServerUrl {\n  const template = server.url;\n  const variables = server.variables ?? {};\n  const unresolved: string[] = [];\n  let url = '';\n  let cursor = 0;\n\n  for (const { name, start, end } of scanPlaceholders(template)) {\n    url += template.slice(cursor, start);\n    // Own keys only: a placeholder named `constructor` or `__proto__` resolves\n    // when the document declares that variable (the parser defines it as an own\n    // data property), never to Object.prototype's member of that name.\n    if (Object.hasOwn(variables, name)) {\n      url += variables[name].default;\n    } else {\n      url += template.slice(start, end);\n      if (!unresolved.includes(name)) unresolved.push(name);\n    }\n    cursor = end;\n  }\n\n  url += template.slice(cursor);\n  return { url, unresolved };\n}\n\n/**\n * The placeholder names a server URL template references, in order of first\n * appearance and without repeats: `['region', 'port']` for\n * `https://{region}.example.com:{port}/{region}`. Read from the template\n * alone, by the same scan as `resolveServerUrl` (so the same literal-brace\n * rules apply), whether or not the server declares a variable for each name.\n *\n * A declared variable whose name is not listed here is one the template never\n * references: its default and its allowed values cannot reach any resolved\n * URL. The differ classifies a change to such a variable as additive on that\n * basis; an emitter that exposes a server's variables can use it to offer\n * only the ones that take effect.\n */\nexport function serverUrlPlaceholders(url: string): string[] {\n  const names: string[] = [];\n  for (const { name } of scanPlaceholders(url)) {\n    if (!names.includes(name)) names.push(name);\n  }\n  return names;\n}\n\n/** One `{name}` in a server URL template: `start` is the index of its `{`, `end` the index just past its `}`. */\ninterface Placeholder {\n  name: string;\n  start: number;\n  end: number;\n}\n\n/**\n * Walk a template's placeholders left to right. A `{` with no closing `}`\n * ends the scan (the rest is literal); an empty `{}` and a `{` that opens\n * another `{` before closing are literal, and scanning resumes right after\n * that `{` so a well-formed placeholder later in the text is still found.\n * The one reading of braces every caller shares, so `resolveServerUrl`,\n * `serverUrlPlaceholders` and `normalizeServerUrl` (through `templateUnits`)\n * cannot disagree about what counts as one.\n */\nfunction* scanPlaceholders(template: string): Generator<Placeholder> {\n  let cursor = 0;\n  while (cursor < template.length) {\n    const open = template.indexOf('{', cursor);\n    if (open === -1) break;\n    const close = template.indexOf('}', open + 1);\n    if (close === -1) break;\n\n    const name = template.slice(open + 1, close);\n    if (name === '' || name.includes('{')) {\n      cursor = open + 1;\n      continue;\n    }\n\n    yield { name, start: open, end: close + 1 };\n    cursor = close + 1;\n  }\n}\n\n/**\n * One unit of a server URL template: a single literal character, or a whole\n * `{name}` placeholder, which is never split, folded or decoded.\n */\ninterface TemplateUnit {\n  text: string;\n  placeholder: boolean;\n}\n\n/**\n * Split a server URL template into literal characters and `{name}`\n * placeholders, read by `scanPlaceholders` so the literal-brace rules are\n * the ones `resolveServerUrl` applies. A literal `{` from an unclosed, empty\n * or reopened brace is a character like any other.\n */\nfunction templateUnits(template: string): TemplateUnit[] {\n  const units: TemplateUnit[] = [];\n  const literal = (text: string): void => {\n    for (const char of text) units.push({ text: char, placeholder: false });\n  };\n  let cursor = 0;\n\n  for (const { start, end } of scanPlaceholders(template)) {\n    literal(template.slice(cursor, start));\n    units.push({ text: template.slice(start, end), placeholder: true });\n    cursor = end;\n  }\n\n  literal(template.slice(cursor));\n  return units;\n}\n\n/** The port each scheme uses when the URL names none (RFC 9110 §4.2, RFC 6455 §3). */\nconst DEFAULT_PORTS: Readonly<Record<string, number>> = { http: 80, https: 443, ws: 80, wss: 443 };\n\n/**\n * A server URL in the form two equivalent spellings share, for comparing\n * server URLs — templates as written and resolved URLs alike. The IR never\n * stores it: `ServerEntry.url` and `ApiSpec.baseUrl` stay as written, and\n * the differ reports every URL as written in the document that declares it.\n *\n * The rules are those of RFC 3986 §6.2.2 (syntax-based) and §6.2.3\n * (scheme-based normalization) that apply to a base URL:\n *\n * - The scheme and the host are case-insensitive and are lower-cased\n *   (`HTTPS://PETS.example.com` and `https://pets.example.com` are one\n *   server). Userinfo, path, query and fragment are case-sensitive and keep\n *   their case, so `/V1` and `/v1` stay two servers.\n * - A port that is empty or is the scheme's default is dropped\n *   (`https://pets.example.com:443`, `https://pets.example.com:` and\n *   `https://pets.example.com` are one server; `http` and `ws` default to\n *   80, `https` and `wss` to 443). Any other port stays.\n * - An empty path after a wholly literal authority is `/`\n *   (`https://pets.example.com` and `https://pets.example.com/` are one\n *   server). Nothing else is done to the path: `/v1` and `/v1/` stay two\n *   servers, and dot-segments are kept.\n * - In a percent-encoded octet the hex digits are upper-cased (`%2f` is\n *   `%2F`) and one that encodes an unreserved character — a letter, a digit,\n *   `-`, `.`, `_` or `~` — is decoded (`%7E` is `~`). Every other octet is\n *   kept encoded, and a `%` not followed by two hex digits is literal.\n *\n * A `{name}` placeholder is kept exactly as written wherever it sits, so a\n * variable name is never case-folded (`{Region}` and `{region}` are different\n * variables) and a template is never confused with what it resolves to\n * (`https://{region}.api.example.com` and `https://eu.api.example.com` stay\n * two servers). A placeholder also ends what can be known about the URL's\n * structure: its value may carry any delimiter — `@` (which makes the text\n * before it in the authority a username), `:` and a port, `/` and a path,\n * `://` and a whole URL — so nothing from the first placeholder on is folded,\n * and a component is folded only when it is complete before that point: the\n * scheme when its `:` comes first, the authority when its end (`/`, `?`, `#`\n * or the end of the template) comes first. So `HTTPS://API.example.com/{v}`\n * is `https://api.example.com/{v}` and `HTTPS://API.example.com{basePath}`\n * is `https://API.example.com{basePath}`, while `…{basePath}` and\n * `…{basePath}/`, `https://{host}:443/v2` and `https://{host}/v2`,\n * `https://USER{suffix}/v1` and `https://user{suffix}/v1` (a `suffix` of\n * `@api.example.com` makes `USER` a username), and `{prefix}://api.example.com`\n * and `{prefix}://api.example.com/` (a `prefix` of\n * `https://gateway.example.com/path` makes the rest a path) all stay two\n * servers. From the first placeholder on not even percent-encoding is\n * folded, and neither is it in an authority the placeholder sits in: a value\n * may put the text in a scheme or a port, where `%` has no meaning\n * (`{scheme}%73://…` and `{scheme}s://…`, `…{x}%34%34%33` and `…{x}443`,\n * `https://api.example.com:4{port}` and `https://api.example.com:%34{port}`,\n * `{scheme}://host:%34%34%33` and `{scheme}://host:443` stay two servers),\n * or end in a `%` that joins with the text after it into a different octet\n * (`https://{host}/{x}7e` and `https://{host}/{x}%37e` stay two servers).\n * Percent-encoding before the first placeholder in a path, query or\n * fragment is folded, since a complete octet there is a complete octet under\n * every value. Every folding therefore applies to text whose part and bytes\n * no variable value can change, and two templates that come out as one\n * string resolve to one URL under every value of their variables. Not folded at\n * all: dot-segments (`/v1/../v2` is compared as written) and\n * internationalised host names (`bücher.example.com` and\n * `xn--bcher-kva.example.com` are two hosts). A relative reference (`/v1`,\n * `//api.example.com/v1`) goes through the same rules from wherever its\n * syntax starts.\n */\nexport function normalizeServerUrl(url: string): string {\n  const units = templateUnits(url);\n  // A placeholder's value may carry any delimiter, so it can change which\n  // part every later character belongs to and, through a `@`, which part\n  // the text before it in its authority belongs to; it may also end in a `%`\n  // or a partial escape that joins with the text after it into a different\n  // percent-encoded octet. So from the first placeholder on nothing is\n  // folded, not even percent-encoding, and a component before it is folded\n  // only when it is complete before that point. Percent-encoding before the\n  // first placeholder in a path, query or fragment is folded: a complete\n  // octet there is a complete octet under every value.\n  const firstPlaceholder = units.findIndex((unit) => unit.placeholder);\n  const literalEnd = firstPlaceholder === -1 ? units.length : firstPlaceholder;\n  /** Units `from` to `to` as written. */\n  const verbatim = (from: number, to: number): string => render(units.slice(from, to), (text) => text);\n  /** Units `from` to `to`: percent-encoding folded before the first placeholder, as written from it on. */\n  const emit = (from: number, to: number): string =>\n    render(units.slice(from, Math.min(to, literalEnd)), normalizePercentEncoding) +\n    verbatim(Math.max(from, literalEnd), to);\n  let out = '';\n  let cursor = 0;\n\n  // Scheme: the units before the first `:`, provided every character among\n  // them may appear in a scheme and the first one is a letter (RFC 3986\n  // §3.1); a `/`, `?`, `#` or `@` before any `:` makes the URL a relative\n  // reference with no scheme. Folded only when that `:` comes before the\n  // first placeholder: a scheme with a placeholder in it (`{prefix}://…`)\n  // may resolve to anything, so the whole template is kept as written.\n  const schemeEnd = schemeLength(units);\n  let scheme: string | undefined;\n  if (schemeEnd !== undefined && schemeEnd >= literalEnd) return verbatim(0, units.length);\n  if (schemeEnd !== undefined) {\n    scheme = render(units.slice(0, schemeEnd), (text) => text.toLowerCase());\n    out += scheme + ':';\n    cursor = schemeEnd + 1;\n  }\n\n  // Authority: after `//`, up to the first `/`, `?` or `#`. Folded only when\n  // that end comes before the first placeholder: a placeholder inside the\n  // authority may resolve to a host suffix, a port, a path, or a `@` that\n  // makes the text before it a username, so an authority with one is kept\n  // as written from its `//` on — the text before the placeholder included,\n  // which may be a port (`:4{port}`), where `%` is not decoded — and gets no\n  // `/` for an empty path.\n  let literalAuthority = false;\n  if (isLiteral(units[cursor], '/') && isLiteral(units[cursor + 1], '/')) {\n    const start = cursor + 2;\n    cursor = start;\n    while (cursor < units.length && !isLiteral(units[cursor], '/', '?', '#')) cursor++;\n    literalAuthority = cursor <= literalEnd;\n    out += '//' + (literalAuthority ? normalizeAuthority(units.slice(start, cursor), scheme) : verbatim(start, cursor));\n  }\n\n  // Path: up to the first `?` or `#`; `/` when a wholly literal authority is\n  // followed by none (`…{basePath}` and `…{basePath}/` stay two templates).\n  const pathStart = cursor;\n  while (cursor < units.length && !isLiteral(units[cursor], '?', '#')) cursor++;\n  const path = emit(pathStart, cursor);\n  out += literalAuthority && path === '' ? '/' : path;\n\n  // Query and fragment: kept as written, percent-encoding aside.\n  out += emit(cursor, units.length);\n  return out;\n}\n\n/** The number of units before the `:` that ends a scheme, or `undefined` when the URL has none. */\nfunction schemeLength(units: TemplateUnit[]): number | undefined {\n  for (let i = 0; i < units.length; i++) {\n    const unit = units[i];\n    if (unit.placeholder) continue;\n    if (unit.text === ':') return i > 0 ? i : undefined;\n    const char = unit.text;\n    const first = i === 0;\n    if (isAlpha(char) || (!first && (isDigit(char) || char === '+' || char === '-' || char === '.'))) continue;\n    return undefined;\n  }\n  return undefined;\n}\n\n/**\n * A wholly literal authority with userinfo kept as written, the host\n * lower-cased and a port that is empty or the scheme's default dropped. The\n * port is what follows the last `:` after any `]` that closes an IP literal,\n * so the colons inside `[2001:db8::1]` are never read as one.\n */\nfunction normalizeAuthority(units: TemplateUnit[], scheme: string | undefined): string {\n  const at = units.findIndex((unit) => isLiteral(unit, '@'));\n  const hostUnits = units.slice(at + 1);\n  let closeBracket = -1;\n  for (let i = hostUnits.length - 1; i >= 0; i--) {\n    if (isLiteral(hostUnits[i], ']')) {\n      closeBracket = i;\n      break;\n    }\n  }\n  let colon = -1;\n  for (let i = hostUnits.length - 1; i > closeBracket; i--) {\n    if (isLiteral(hostUnits[i], ':')) {\n      colon = i;\n      break;\n    }\n  }\n\n  if (colon === -1) return foldUserinfoAndHost(units);\n\n  const port = render(hostUnits.slice(colon + 1), (text) => text);\n  const withoutPort = foldUserinfoAndHost(units.slice(0, at + 1 + colon));\n  if (port === '' || isDefaultPort(port, scheme)) return withoutPort;\n  return withoutPort + ':' + port;\n}\n\n/** Userinfo — up to the first `@` — as written and the host lower-cased, percent-encoding normalised in both. */\nfunction foldUserinfoAndHost(units: TemplateUnit[]): string {\n  const at = units.findIndex((unit) => isLiteral(unit, '@'));\n  const userinfo = at === -1 ? '' : render(units.slice(0, at), normalizePercentEncoding) + '@';\n  return userinfo + render(units.slice(at + 1), foldHost);\n}\n\n/**\n * A host lower-cased outside its percent-encoded octets, which keep their\n * upper-cased hex digits (`p%C3%A9ts.EXAMPLE.com` is `p%C3%A9ts.example.com`);\n * an octet that encodes a letter is decoded first and so lower-cased too\n * (`%41PI` is `api`).\n */\nfunction foldHost(text: string): string {\n  const encoded = normalizePercentEncoding(text);\n  let out = '';\n  for (let i = 0; i < encoded.length; i++) {\n    const char = encoded[i];\n    if (char === '%' && i + 2 < encoded.length && isHexDigit(encoded[i + 1]) && isHexDigit(encoded[i + 2])) {\n      out += encoded.slice(i, i + 3);\n      i += 2;\n    } else {\n      out += char.toLowerCase();\n    }\n  }\n  return out;\n}\n\n/** Whether a literal port, read as a decimal number, is the one `scheme` implies. */\nfunction isDefaultPort(port: string, scheme: string | undefined): boolean {\n  if (scheme === undefined || !Object.hasOwn(DEFAULT_PORTS, scheme)) return false;\n  for (const char of port) if (!isDigit(char)) return false;\n  return Number(port) === DEFAULT_PORTS[scheme];\n}\n\n/**\n * Upper-case the hex digits of every percent-encoded octet and decode the\n * ones that encode an unreserved character (RFC 3986 §6.2.2.1–§6.2.2.2).\n */\nfunction normalizePercentEncoding(text: string): string {\n  let out = '';\n  for (let i = 0; i < text.length; i++) {\n    const char = text[i];\n    if (char === '%' && i + 2 < text.length && isHexDigit(text[i + 1]) && isHexDigit(text[i + 2])) {\n      const hex = text.slice(i + 1, i + 3);\n      const decoded = String.fromCharCode(Number.parseInt(hex, 16));\n      out += isUnreserved(decoded) ? decoded : '%' + hex.toUpperCase();\n      i += 2;\n    } else {\n      out += char;\n    }\n  }\n  return out;\n}\n\n/** Join units back into text, passing each run of literal characters through `transform` and every placeholder as written. */\nfunction render(units: TemplateUnit[], transform: (text: string) => string): string {\n  let out = '';\n  let run = '';\n  for (const unit of units) {\n    if (unit.placeholder) {\n      out += transform(run) + unit.text;\n      run = '';\n    } else {\n      run += unit.text;\n    }\n  }\n  return out + transform(run);\n}\n\n/** Whether `unit` is a literal character that is one of `chars`. */\nfunction isLiteral(unit: TemplateUnit | undefined, ...chars: string[]): boolean {\n  return unit !== undefined && !unit.placeholder && chars.includes(unit.text);\n}\n\nfunction isAlpha(char: string): boolean {\n  return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');\n}\n\nfunction isDigit(char: string): boolean {\n  return char >= '0' && char <= '9';\n}\n\nfunction isHexDigit(char: string): boolean {\n  return isDigit(char) || (char >= 'a' && char <= 'f') || (char >= 'A' && char <= 'F');\n}\n\n/** RFC 3986 §2.3: a character that needs no percent-encoding anywhere in a URI. */\nfunction isUnreserved(char: string): boolean {\n  return isAlpha(char) || isDigit(char) || char === '-' || char === '.' || char === '_' || char === '~';\n}\n\n/**\n * Whether two server lists are the same, entry for entry.\n *\n * Structural: the same length, and at each position the same `url` — up to\n * `normalizeServerUrl`, so a scheme or host that differs only in case, a\n * default port written or not, and a trailing `/` after a bare authority\n * are the same URL, and that form folds nothing a placeholder's value could\n * change, so two entries it calls equal resolve to one URL under every value\n * of their variables, which `resolveAlike` checks value by value all the\n * same — and the same `description` and the same `variables`:\n * the same names, each with the same `default`, the same `enum` (same values\n * in the same order) and the same `description`, all compared as written.\n * Position matters because `servers[0]` is the one a client defaults to. A\n * key that is absent and one set to `undefined` compare equal. Variables are\n * compared by own key only, so one named `__proto__` or `constructor` is\n * compared like any other and never read off `Object.prototype`.\n *\n * The parser uses this to decide whether an operation's effective servers\n * differ from the document's (`Operation.servers` is set only when they do):\n * the IR carries exactly what the document says. The differ's\n * `serversChanged` deliberately uses a looser rule — descriptions, enum order\n * and position ignored, matching the document-level diff — so a description\n * edit sets the field without being reported as a change.\n */\nexport function serverListsEqual(a: readonly ServerEntry[], b: readonly ServerEntry[]): boolean {\n  if (a.length !== b.length) return false;\n  return a.every((entry, i) => serverEntriesEqual(entry, b[i]));\n}\n\nfunction serverEntriesEqual(a: ServerEntry, b: ServerEntry): boolean {\n  if (normalizeServerUrl(a.url) !== normalizeServerUrl(b.url) || a.description !== b.description) return false;\n  const aVariables = a.variables ?? {};\n  const bVariables = b.variables ?? {};\n  const names = Object.keys(aVariables);\n  if (names.length !== Object.keys(bVariables).length) return false;\n  if (\n    !names.every((name) => Object.hasOwn(bVariables, name) && serverVariablesEqual(aVariables[name], bVariables[name]))\n  ) {\n    return false;\n  }\n  // `normalizeServerUrl` folds nothing a placeholder's value could change, so\n  // equal forms with equal variables resolve to one URL under every value;\n  // checked all the same, value by value, so the guarantee does not rest on\n  // that reading alone.\n  return resolveAlike(a, b);\n}\n\n/**\n * Whether every allowed substitution resolves `a` and `b` to the same URL up\n * to `normalizeServerUrl`: the defaults, then each enum value of each\n * variable in turn with every other variable at its default. Both entries\n * are resolved with `a`'s variables, which the caller has found equal to\n * `b`'s. Substituted maps are built with `Object.fromEntries`, so a variable\n * named `__proto__` stays an own key.\n */\nfunction resolveAlike(a: ServerEntry, b: ServerEntry): boolean {\n  const variables = a.variables ?? {};\n  const substitutions: Array<Record<string, ServerVariable>> = [variables];\n  for (const [name, variable] of Object.entries(variables)) {\n    for (const value of variable.enum ?? []) {\n      if (value === variable.default) continue;\n      substitutions.push(\n        Object.fromEntries(\n          Object.entries(variables).map(([other, v]) => [other, other === name ? { ...v, default: value } : v]),\n        ),\n      );\n    }\n  }\n  return substitutions.every(\n    (vars) =>\n      normalizeServerUrl(resolveServerUrl({ url: a.url, variables: vars }).url) ===\n      normalizeServerUrl(resolveServerUrl({ url: b.url, variables: vars }).url),\n  );\n}\n\nfunction serverVariablesEqual(a: ServerVariable, b: ServerVariable): boolean {\n  if (a.default !== b.default || a.description !== b.description) return false;\n  const aEnum = a.enum ?? [];\n  const bEnum = b.enum ?? [];\n  return aEnum.length === bEnum.length && aEnum.every((value, i) => value === bEnum[i]);\n}\n\n/** The server OpenAPI gives a document that declares none: a single entry at `/`. */\nconst DEFAULT_SERVER_URL = '/';\n\n/**\n * Whether a server entry is OpenAPI's default server: its `url` is `/`.\n * Neither its `description` nor its `variables` count. The default server\n * has neither; a description changes nothing about where a request goes; and\n * `/` contains no placeholder (`serverUrlPlaceholders('/')` is empty), so a\n * variable declared on it is never referenced and cannot change where it\n * points either (#292). A template that merely resolves to `/` (a referenced\n * variable whose default is `/`) is a template, not the default server.\n */\nexport function isDefaultServerEntry(server: ServerEntry): boolean {\n  // `/` is its own RFC 3986 form; read through `normalizeServerUrl` so that\n  // every server URL comparison in this module goes through one function.\n  return normalizeServerUrl(server.url) === DEFAULT_SERVER_URL;\n}\n\n/**\n * Whether a server list means OpenAPI's default server. OpenAPI gives a\n * document with no `servers`, or `servers: []`, a single server at `/`; a\n * document that writes that server out declares nothing beyond it, and\n * neither does one that writes it out twice. So `undefined`, an empty list,\n * and a list whose every entry is the default by `isDefaultServerEntry` are\n * all the default. A list with any other entry is not, wherever `/` sits in\n * it, because position decides the default host.\n *\n * The parser asks this of an operation's list and the document's: both at\n * the default means the operation inherits (`Operation.servers`, #291). The\n * differ asks it to tell the `/` a document is only implied to have, which\n * is never reported as added or removed, from one it lists beside another\n * server, which is.\n */\nexport function isDefaultServerList(servers: readonly ServerEntry[] | undefined): boolean {\n  return !servers || servers.every(isDefaultServerEntry);\n}\n\n/**\n * The servers a document is served from: its list as written (the same\n * array, not a copy) when it declares anything beyond the default, else\n * OpenAPI's default server, a single `{ url: '/' }`. A document without\n * `servers`, one with `servers: []`, one whose only server is `/`, and one\n * that writes `/` out twice all come out as `[{ url: '/' }]` (a description\n * on the entry is not carried: the default server has none), while\n * `[/, host]` stays `[/, host]`, because there `/` is a server the document\n * lists, not one it is implied to have. The differ matches servers on this,\n * so the three spellings of the default pair with each other and with a `/`\n * listed beside a host.\n */\nexport function serversOrDefault(servers: readonly ServerEntry[] | undefined): readonly ServerEntry[] {\n  return servers && !isDefaultServerList(servers) ? servers : [{ url: DEFAULT_SERVER_URL }];\n}\n\n/**\n * A document's default address beyond OpenAPI's default: `''` when\n * `baseUrl` is `''` (the parser's value for a document with no server) or\n * `/` (the resolved address of the default server, written out or not),\n * else `baseUrl` as given. The differ compares `base-url-changed` on this,\n * so the three spellings of the default share one address and a document\n * whose first server merely resolves to `/` has not moved from it. Any other\n * `baseUrl` — a host, or `/v1` — is compared as written, even with no\n * `servers` beside it (an IR built by hand, which the parser never\n * produces).\n */\nexport function baseUrlBeyondDefault(baseUrl: string): string {\n  // Read through `normalizeServerUrl` like every other server URL comparison\n  // in this module; `/` is its own form, so only `/` itself is the default.\n  return normalizeServerUrl(baseUrl) === DEFAULT_SERVER_URL ? '' : baseUrl;\n}\n","/**\n * How one parameter is told apart from another on an operation, a webhook or\n * a response. OpenAPI identifies a parameter by its `name` and its `in`\n * location — a path `id` may sit beside a query `id` — so the two are\n * compared together. Header names are case-insensitive (RFC 9110 §5.1), so a\n * header's name is folded before it is compared; path, query and cookie\n * names are case-sensitive and compared as written. The IR keeps every name\n * as written: only the comparison folds. Every place that asks whether two\n * parameters are the same one — the parser merging a path item's parameters\n * with an operation's, the parser reading a response's `headers` map, the\n * differ pairing a parameter across two documents — goes through this\n * module, so one rule answers it.\n */\n\n/** Where a parameter lives, as OpenAPI's `in` names it. */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie';\n\n/**\n * A header name as it is compared: lower-cased, since RFC 9110 §5.1 makes\n * header names case-insensitive (`X-Request-Id` and `x-request-id` name one\n * header). A header name is an ASCII token, so plain case folding is exact.\n * It is also the name the parser mints a header's inline model or enum\n * from (`X-RateLimit-Policy` → `…XRatelimitPolicy`, whatever its case), so\n * two spellings of one header type the same way; the IR's `name` stays as\n * written.\n */\nexport function foldHeaderName(name: string): string {\n  return name.toLowerCase();\n}\n\n/**\n * A parameter name as it is compared at `location`: a header's is folded by\n * `foldHeaderName`; a path, query or cookie name is case-sensitive and kept\n * as written (`Limit` and `limit` are two query parameters). It is also the\n * name the parser mints a parameter's inline model or enum from, so a\n * header's type name does not move with the header's case.\n */\nexport function foldParameterName(location: ParameterLocation, name: string): string {\n  return location === 'header' ? foldHeaderName(name) : name;\n}\n\n/**\n * The identity of a parameter within one operation or webhook:\n * `location:name`, the name folded by `foldParameterName`. Two parameters\n * with one key are one parameter — the parser lets the later declaration\n * (an operation's over its path item's) replace the earlier, and the differ\n * pairs the old and new declarations rather than reporting a removal beside\n * an addition.\n */\nexport function parameterKey(location: ParameterLocation, name: string): string {\n  return `${location}:${foldParameterName(location, name)}`;\n}\n","import { toPascalCase } from './naming.js';\n\n/** One `name=value` parameter of a media type, the name lower-cased and the value decoded. */\nexport interface MediaTypeParameter {\n  name: string;\n  value: string;\n}\n\n/** A media type read into its essence and its parameters (`parseMediaType`). */\nexport interface ParsedMediaType {\n  /** `type/subtype`, trimmed and lower-cased. */\n  essence: string;\n  /** The parameters in document order, names lower-cased, quoted values decoded. */\n  parameters: MediaTypeParameter[];\n}\n\n/**\n * A media type read as RFC 9110 §8.3.1 writes it: `type/subtype`, then\n * `;`-separated `name=value` parameters whose value is a token or a\n * quoted-string. A `;` inside a quoted-string does not end a parameter\n * (`profile=\"https://example.com/a;b\"` is one parameter), a backslash inside\n * one escapes the next character (`\"say \\\"hi\\\"\"` reads `say \"hi\"`), and the\n * quotes are not part of the value. The essence is trimmed and lower-cased,\n * and so is every parameter name (they are case-insensitive); a value keeps\n * its case, since whether it matters depends on the parameter. A parameter\n * written without `=` has the empty value, an empty segment (`a;;b`) is\n * skipped, and a quoted-string nobody closes runs to the end of the key.\n * This is the one reader every media-type question goes through — the\n * essence, the model-name fragment and the differ's comparison of\n * parameters — so they agree on where a parameter ends.\n */\nexport function parseMediaType(contentType: string): ParsedMediaType {\n  const segments: string[] = [];\n  let segment = '';\n  let quoted = false;\n  for (let i = 0; i < contentType.length; i++) {\n    const char = contentType[i];\n    if (quoted) {\n      if (char === '\\\\' && i + 1 < contentType.length) {\n        segment += char + contentType[++i];\n        continue;\n      }\n      if (char === '\"') quoted = false;\n      segment += char;\n      continue;\n    }\n    if (char === ';') {\n      segments.push(segment);\n      segment = '';\n      continue;\n    }\n    if (char === '\"') quoted = true;\n    segment += char;\n  }\n  segments.push(segment);\n  const [first = '', ...rest] = segments;\n  const parameters: MediaTypeParameter[] = [];\n  for (const raw of rest) {\n    const parameter = raw.trim();\n    if (parameter.length === 0) continue;\n    const separator = parameter.indexOf('=');\n    const name = (separator === -1 ? parameter : parameter.slice(0, separator)).trim().toLowerCase();\n    const value = separator === -1 ? '' : unquote(parameter.slice(separator + 1).trim());\n    parameters.push({ name, value });\n  }\n  return { essence: first.trim().toLowerCase(), parameters };\n}\n\n/** A parameter value decoded: a quoted-string without its quotes and with its escapes resolved, a token as written. */\nfunction unquote(raw: string): string {\n  if (!raw.startsWith('\"')) return raw;\n  let value = '';\n  for (let i = 1; i < raw.length; i++) {\n    const char = raw[i];\n    if (char === '\\\\' && i + 1 < raw.length) {\n      value += raw[++i];\n      continue;\n    }\n    if (char === '\"') break;\n    value += char;\n  }\n  return value;\n}\n\n/**\n * A media type's essence — `type/subtype` without parameters, trimmed and\n * lower-cased (RFC 9110 §8.3.1): `application/json; charset=utf-8`,\n * `APPLICATION/JSON` and ` application/json ` are all `application/json`.\n * The essence is what decides how a request or response body is typed and\n * encoded; the content keys themselves stay as written wherever the IR\n * carries them (`responseContentTypes`, `contentTypes`).\n */\nexport function mediaTypeEssence(contentType: string): string {\n  return parseMediaType(contentType).essence;\n}\n\n/**\n * Whether a media type is `application/json` itself, by essence\n * (`application/json; charset=utf-8`, `APPLICATION/JSON`): the JSON\n * spelling a request body pick and a response body read prefer over a\n * `+json` type declared beside it.\n */\nexport function isPlainJsonMediaType(contentType: string): boolean {\n  return mediaTypeEssence(contentType) === 'application/json';\n}\n\n/**\n * Whether a media type is JSON by essence: `application/json` itself, or any\n * type with the `+json` structured-syntax suffix (`application/vnd.api+json`,\n * `application/merge-patch+json`, `application/problem+json`). The one rule\n * for what a JSON body is, on a request and on a response alike; which JSON\n * spelling wins when several are declared is `isPlainJsonMediaType`'s.\n */\nexport function isJsonMediaType(contentType: string): boolean {\n  const essence = mediaTypeEssence(contentType);\n  return essence === 'application/json' || essence.endsWith('+json');\n}\n\n/**\n * The PascalCase fragment that qualifies a model minted for a non-primary\n * media type among the `content` keys it is declared beside (`siblings`,\n * the key itself included or not): the essence's token (`text/html` →\n * `TextHtml`, `application/json; charset=utf-8` → `ApplicationJson`), so a\n * key keeps its model name however it is spelled — plus the key's own\n * parameters (`application/yaml; charset=utf-8` → `ApplicationYamlCharsetUtf8`)\n * only when another key of the same essence sits beside it, so two spellings\n * of one essence declared side by side take names that do not depend on\n * their order. Parameters are read by `parseMediaType` (a `;` inside a\n * quoted value does not split one) and lower-cased before casing, so\n * `Charset=UTF-8` and `charset=utf-8` agree; their order is kept. A\n * wildcard segment reads as `Any` (`application/*` → `ApplicationAny`);\n * nothing left reads as `Content`.\n */\nexport function mediaTypeNameFragment(contentType: string, siblings: Iterable<string> = []): string {\n  const { essence, parameters } = parseMediaType(contentType);\n  const token = toPascalCase(essence.split('*').join('Any'));\n  const shared =\n    parameters.length > 0 &&\n    [...siblings].some((sibling) => sibling !== contentType && mediaTypeEssence(sibling) === essence);\n  const fragment = shared\n    ? `${token}${toPascalCase(parameters.map((parameter) => `${parameter.name} ${parameter.value}`.toLowerCase()).join(' '))}`\n    : token;\n  return fragment.length > 0 ? fragment : 'Content';\n}\n","import type Parser from 'tree-sitter';\nimport type { UrlFingerprintConfig } from './types.js';\n\n/**\n * Extract a URL path fingerprint from a method body using tree-sitter AST traversal.\n *\n * Walks the AST subtree of the member node looking for the first string literal\n * that starts with '/'. Normalizes interpolation expressions to '{}' and format\n * specifiers (%s, %d, etc.) to '{}' for cross-language comparison.\n *\n * @returns A normalized URL fingerprint like \"/organizations/{}\" or undefined if none found.\n */\nexport function extractUrlFingerprint(memberNode: Parser.SyntaxNode, config: UrlFingerprintConfig): string | undefined {\n  const stringTypes = new Set(config.stringNodeTypes);\n  const contentTypes = new Set(config.contentNodeTypes);\n  const interpolationTypes = new Set(config.interpolationNodeTypes);\n  const formatFns = config.formatFunctionNames ? new Set(config.formatFunctionNames) : null;\n\n  // Iterative DFS through the method's AST subtree\n  const stack: Parser.SyntaxNode[] = [memberNode];\n\n  while (stack.length > 0) {\n    const node = stack.pop()!;\n\n    if (stringTypes.has(node.type)) {\n      const fp = resolveFingerprint(node, contentTypes, interpolationTypes);\n      if (fp?.startsWith('/')) return fp;\n    }\n\n    // For format functions (Go's Sprintf, Rust's format!): check if this call\n    // matches and extract the first string argument.\n    if (formatFns && isFormatCall(node, formatFns)) {\n      const fp = extractFromFormatCall(node, stringTypes, contentTypes, interpolationTypes);\n      if (fp?.startsWith('/')) return fp;\n    }\n\n    // Push children in reverse order so leftmost child is processed first\n    for (let i = node.childCount - 1; i >= 0; i--) {\n      const child = node.child(i);\n      if (child) stack.push(child);\n    }\n  }\n\n  return undefined;\n}\n\n/**\n * Resolve the text content of a string node, normalizing interpolations to '{}'.\n */\nfunction resolveFingerprint(\n  stringNode: Parser.SyntaxNode,\n  contentTypes: Set<string>,\n  interpolationTypes: Set<string>,\n): string | undefined {\n  // Leaf string node (no children besides quotes) — strip quotes\n  if (stringNode.namedChildCount === 0) {\n    return normalizeFormatSpecifiers(stripQuotes(stringNode.text));\n  }\n\n  // Composite string (has content fragments + interpolation children)\n  let result = '';\n  for (let i = 0; i < stringNode.childCount; i++) {\n    const child = stringNode.child(i)!;\n    if (contentTypes.has(child.type)) {\n      result += child.text;\n    } else if (interpolationTypes.has(child.type)) {\n      result += '{}';\n    }\n    // Skip quote delimiters, interpolation markers, etc.\n  }\n\n  return result ? normalizeFormatSpecifiers(result) : normalizeFormatSpecifiers(stripQuotes(stringNode.text));\n}\n\n/** Check if a node is a call to one of the format functions (e.g., fmt.Sprintf, format!). */\nfunction isFormatCall(node: Parser.SyntaxNode, formatFns: Set<string>): boolean {\n  // Rust macro: format!(...) — tree-sitter may parse as macro_invocation\n  if (node.type === 'macro_invocation') {\n    const macroName = node.childForFieldName('macro')?.text;\n    return !!(macroName && formatFns.has(macroName.replace(/!$/, '')));\n  }\n\n  if (node.type !== 'call_expression') return false;\n  const fnNode = node.childForFieldName('function');\n  if (!fnNode) return false;\n\n  // Direct call: Sprintf(...) or format!(...)\n  if (formatFns.has(fnNode.text)) return true;\n\n  // Member call: fmt.Sprintf(...)\n  if (fnNode.type === 'selector_expression' || fnNode.type === 'member_expression') {\n    const prop = fnNode.childForFieldName('field') ?? fnNode.childForFieldName('property');\n    if (prop && formatFns.has(prop.text)) return true;\n  }\n  return false;\n}\n\n/** Extract the first string argument from a format function call. */\nfunction extractFromFormatCall(\n  callNode: Parser.SyntaxNode,\n  stringTypes: Set<string>,\n  contentTypes: Set<string>,\n  interpolationTypes: Set<string>,\n): string | undefined {\n  const args = callNode.childForFieldName('arguments');\n  if (!args) return undefined;\n\n  for (let i = 0; i < args.childCount; i++) {\n    const arg = args.child(i)!;\n    if (stringTypes.has(arg.type)) {\n      return resolveFingerprint(arg, contentTypes, interpolationTypes);\n    }\n  }\n  return undefined;\n}\n\n/** Strip surrounding quote characters from a string literal. */\nfunction stripQuotes(text: string): string {\n  // Handle various quote styles: \"...\", '...', `...`, f\"...\", $\"...\", @\"...\"\n  const match = text.match(/^(?:f|r|b|@|\\$)?(?:\"\"\"([\\s\\S]*)\"\"\"|'''([\\s\\S]*)'''|\"(.*)\"|'(.*)'|`(.*)`)$/s);\n  if (match) return match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5] ?? text;\n  return text;\n}\n\n/** Replace printf-style format specifiers (%s, %d, %v, %f) with {}. */\nfunction normalizeFormatSpecifiers(s: string): string {\n  return s.replace(/%[sdvf]/g, '{}');\n}\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst DOTNET_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string_literal', 'interpolated_string_expression'],\n  contentNodeTypes: ['string_content', 'string_literal_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nconst DECLARATION_TYPES = new Set([\n  'class_declaration',\n  'struct_declaration',\n  'interface_declaration',\n  'enum_declaration',\n  'record_declaration',\n]);\n\nfunction extractDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (DECLARATION_TYPES.has(node.type)) {\n    const nameNode = node.childForFieldName('name') ?? node.children.find((c) => c.type === 'identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'namespace_declaration' || node.type === 'file_scoped_namespace_declaration') {\n    const nameNode =\n      node.children.find((c) => c.type === 'qualified_name') ?? node.children.find((c) => c.type === 'identifier');\n    return nameNode ? `__namespace:${nameNode.text}` : null;\n  }\n  return null;\n}\n\nfunction collectPrecedingXmlDocComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('///')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\n/**\n * Collect declarations from a list of sibling nodes (root level or namespace body).\n */\nfunction collectDeclarations(\n  children: Parser.SyntaxNode[],\n  source: string,\n  statements: MergeStatement[],\n  imports: MergeImport[],\n  importAnchors: string[],\n  importInsertionAnchor: { value?: string },\n): void {\n  for (const child of children) {\n    if (child.type === 'comment') continue;\n\n    if (child.type === 'using_directive') {\n      const text = source.slice(child.startIndex, child.endIndex);\n      imports.push({ key: text.trim(), text });\n      importAnchors.push(text);\n      continue;\n    }\n\n    if (child.type === 'file_scoped_namespace_declaration') {\n      importInsertionAnchor.value = source.slice(child.startIndex, child.endIndex);\n      // File-scoped namespace: subsequent declarations are siblings at root\n      continue;\n    }\n\n    if (child.type === 'namespace_declaration') {\n      importInsertionAnchor.value = source.slice(child.startIndex, child.endIndex);\n      // Block namespace: recurse into declaration_list\n      const body = child.children.find((c) => c.type === 'declaration_list');\n      if (body) {\n        collectDeclarations(body.namedChildren, source, statements, imports, importAnchors, importInsertionAnchor);\n      }\n      continue;\n    }\n\n    const name = extractDeclarationName(child);\n    statements.push({\n      key: name,\n      kind: name ? 'declaration' : 'other',\n      text: source.slice(child.startIndex, child.endIndex),\n    });\n  }\n}\n\nexport const dotnetMergeAdapter: MergeAdapter = {\n  language: 'dotnet',\n  grammarModule: 'tree-sitter-c-sharp',\n  testFilePatterns: [/Tests?\\.cs$/],\n  urlFingerprintConfig: DOTNET_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n    const importInsertionAnchor: { value?: string } = {};\n\n    collectDeclarations(tree.rootNode.children, source, statements, imports, importAnchors, importInsertionAnchor);\n\n    return {\n      imports,\n      importAnchors,\n      importInsertionAnchor: importInsertionAnchor.value,\n      statements,\n    };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n\n    function processChildren(children: Parser.SyntaxNode[]): void {\n      for (let i = 0; i < children.length; i++) {\n        const child = children[i];\n\n        // Recurse into namespaces\n        if (child.type === 'namespace_declaration') {\n          const body = child.children.find((c) => c.type === 'declaration_list');\n          if (body) processChildren(body.children);\n          continue;\n        }\n\n        const name = extractDeclarationName(child);\n        if (!name || name.startsWith('__namespace:')) continue;\n\n        const docstring = collectPrecedingXmlDocComments(children, i, source);\n        const members = new Map<string, MemberDocstrings>();\n\n        // Extract member docstrings\n        const body = child.children.find((c) => c.type === 'declaration_list');\n        if (body) {\n          const bodyChildren = body.children;\n          for (let j = 0; j < bodyChildren.length; j++) {\n            const member = bodyChildren[j];\n            if (member.type !== 'method_declaration' && member.type !== 'property_declaration') continue;\n            // For methods, the second identifier is the name (first is return type)\n            const identifiers = member.children.filter((c) => c.type === 'identifier');\n            const memberName =\n              member.type === 'method_declaration'\n                ? identifiers.length >= 2\n                  ? identifiers[1]!.text\n                  : identifiers[0]?.text\n                : identifiers[0]?.text;\n            if (!memberName) continue;\n            const memberDoc = collectPrecedingXmlDocComments(bodyChildren, j, source);\n            members.set(memberName, {\n              docstring: memberDoc,\n              declStartIndex: member.startIndex,\n              declColumn: member.startPosition.column,\n              urlFingerprint: extractUrlFingerprint(member, DOTNET_URL_FINGERPRINT_CONFIG),\n            });\n          }\n        }\n\n        result.set(name, {\n          docstring,\n          declStartIndex: child.startIndex,\n          declColumn: child.startPosition.column,\n          members,\n        });\n      }\n    }\n\n    processChildren(tree.rootNode.children);\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst ELIXIR_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string'],\n  contentNodeTypes: ['quoted_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nfunction isDefmodule(node: Parser.SyntaxNode): boolean {\n  return node.type === 'call' && node.children[0]?.text === 'defmodule';\n}\n\nfunction getModuleName(node: Parser.SyntaxNode): string | null {\n  if (!isDefmodule(node)) return null;\n  const args = node.children.find((c) => c.type === 'arguments');\n  if (!args) return null;\n  const alias = args.children.find((c) => c.type === 'alias');\n  return alias?.text ?? null;\n}\n\nfunction getDoBlock(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  return node.children.find((c) => c.type === 'do_block') ?? null;\n}\n\n/** Check if a node is an @moduledoc or @doc attribute. */\nfunction isDocAttribute(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'unary_operator') return null;\n  const call = node.children.find((c) => c.type === 'call');\n  if (!call) return null;\n  const id = call.children.find((c) => c.type === 'identifier');\n  if (id?.text === 'moduledoc' || id?.text === 'doc') return id.text;\n  return null;\n}\n\n/** Check if a node is a def/defp call. */\nfunction getDefName(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'call') return null;\n  const id = node.children[0];\n  if (!id || (id.text !== 'def' && id.text !== 'defp')) return null;\n  const args = node.children.find((c) => c.type === 'arguments');\n  if (!args) return null;\n  // The function name is either a simple identifier or a call (for functions with params)\n  for (const arg of args.namedChildren) {\n    if (arg.type === 'identifier') return arg.text;\n    if (arg.type === 'call') {\n      const nameNode = arg.children.find((c) => c.type === 'identifier');\n      return nameNode?.text ?? null;\n    }\n  }\n  return null;\n}\n\n/** Check if a node is an alias/import/require/use call. */\nfunction isImportLike(node: Parser.SyntaxNode): boolean {\n  if (node.type !== 'call') return false;\n  const id = node.children[0];\n  return id?.type === 'identifier' && ['alias', 'import', 'require', 'use'].includes(id.text);\n}\n\nexport const elixirMergeAdapter: MergeAdapter = {\n  language: 'elixir',\n  grammarModule: 'tree-sitter-elixir',\n  testFilePatterns: [/_test\\.exs$/],\n  urlFingerprintConfig: ELIXIR_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      // Top-level alias/import/require/use (rare but possible outside modules)\n      if (isImportLike(child)) {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const moduleName = getModuleName(child);\n      statements.push({\n        key: moduleName,\n        kind: moduleName ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const moduleName = getModuleName(child);\n      if (!moduleName) continue;\n\n      // Look for @moduledoc inside the do_block\n      let docstring: DocstringInfo | null = null;\n      const doBlock = getDoBlock(child);\n      const members = new Map<string, MemberDocstrings>();\n\n      if (doBlock) {\n        const bodyChildren = doBlock.children;\n\n        // Find @moduledoc\n        for (const bodyChild of bodyChildren) {\n          if (isDocAttribute(bodyChild) === 'moduledoc') {\n            docstring = {\n              text: source.slice(bodyChild.startIndex, bodyChild.endIndex),\n              startIndex: bodyChild.startIndex,\n              endIndex: bodyChild.endIndex,\n            };\n            break;\n          }\n        }\n\n        // Find @doc + def pairs for member docstrings\n        for (let j = 0; j < bodyChildren.length; j++) {\n          const bodyChild = bodyChildren[j];\n          const defName = getDefName(bodyChild);\n          if (!defName) continue;\n\n          // Look for preceding @doc attribute\n          let memberDoc: DocstringInfo | null = null;\n          for (let k = j - 1; k >= 0; k--) {\n            const prev = bodyChildren[k];\n            if (isDocAttribute(prev) === 'doc') {\n              memberDoc = {\n                text: source.slice(prev.startIndex, prev.endIndex),\n                startIndex: prev.startIndex,\n                endIndex: prev.endIndex,\n              };\n              break;\n            }\n            if (prev.type === 'comment') continue;\n            break;\n          }\n\n          members.set(defName, {\n            docstring: memberDoc,\n            declStartIndex: bodyChild.startIndex,\n            declColumn: bodyChild.startPosition.column,\n            urlFingerprint: extractUrlFingerprint(bodyChild, ELIXIR_URL_FINGERPRINT_CONFIG),\n          });\n        }\n      }\n\n      result.set(moduleName, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type { MergeAdapter, MergeStatement, MergeImport, DocstringInfo, SymbolDocstrings } from './types.js';\n\nconst GO_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['interpreted_string_literal'],\n  contentNodeTypes: ['interpreted_string_literal_content'],\n  interpolationNodeTypes: [],\n  formatFunctionNames: ['Sprintf'],\n};\n\nfunction lastIdentifier(text: string): string | null {\n  const matches = [...text.matchAll(/[A-Za-z_][A-Za-z0-9_]*/g)];\n  return matches.length > 0 ? matches[matches.length - 1]![0] : null;\n}\n\nfunction receiverKey(node: Parser.SyntaxNode): string | null {\n  const receiver = node.childForFieldName('receiver');\n  if (!receiver) return null;\n  return lastIdentifier(receiver.text);\n}\n\nfunction declarationKey(node: Parser.SyntaxNode): string | null {\n  switch (node.type) {\n    case 'package_clause': {\n      const pkg = lastIdentifier(node.text);\n      return pkg ? `__package:${pkg}` : '__package:';\n    }\n    case 'type_declaration': {\n      const spec = node.firstNamedChild?.type === 'type_spec' ? node.firstNamedChild : node.namedChildren[0];\n      const nameNode = spec?.childForFieldName('name');\n      return nameNode?.text ?? null;\n    }\n    case 'function_declaration': {\n      return node.childForFieldName('name')?.text ?? null;\n    }\n    case 'method_declaration': {\n      const name = node.childForFieldName('name')?.text ?? null;\n      const receiver = receiverKey(node);\n      return name && receiver ? `method:${receiver}.${name}` : name;\n    }\n    case 'const_declaration':\n    case 'var_declaration': {\n      return node.text.split(/\\s+/).slice(0, 3).join(' ');\n    }\n    default:\n      return null;\n  }\n}\n\nfunction importEntries(node: Parser.SyntaxNode, source: string): MergeImport[] {\n  const entries: MergeImport[] = [];\n\n  const collect = (spec: Parser.SyntaxNode): void => {\n    const path = spec.childForFieldName('path')?.text ?? spec.text;\n    const name = spec.childForFieldName('name')?.text ?? '';\n    const text = source.slice(spec.startIndex, spec.endIndex);\n    entries.push({\n      key: `${name}:${path.replace(/^\"|\"$/g, '')}`,\n      text,\n    });\n  };\n\n  for (const child of node.namedChildren) {\n    if (child.type === 'import_spec') {\n      collect(child);\n      continue;\n    }\n    if (child.type === 'import_spec_list') {\n      for (const spec of child.namedChildren) {\n        if (spec.type === 'import_spec') collect(spec);\n      }\n    }\n  }\n\n  return entries;\n}\n\nfunction collectPrecedingGoComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('//')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const goMergeAdapter: MergeAdapter = {\n  language: 'go',\n  grammarModule: 'tree-sitter-go',\n  testFilePatterns: [/_test\\.go$/],\n  urlFingerprintConfig: GO_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    let importInsertionAnchor: string | undefined;\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'package_clause') {\n        importInsertionAnchor = source.slice(child.startIndex, child.endIndex);\n      }\n\n      if (child.type === 'import_declaration') {\n        imports.push(...importEntries(child, source));\n        importAnchors.push(source.slice(child.startIndex, child.endIndex));\n        continue;\n      }\n\n      const key = declarationKey(child);\n      statements.push({\n        key,\n        kind: key ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, importInsertionAnchor, statements };\n  },\n  renderImports(imports) {\n    if (imports.length === 0) return [];\n    if (imports.length === 1) return [`import ${imports[0]!.text}`];\n    return [`import (\\n${imports.map((entry) => `  ${entry.text}`).join('\\n')}\\n)`];\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const key = declarationKey(child);\n      if (!key || key.startsWith('__package:')) continue;\n\n      const docstring = collectPrecedingGoComments(rootChildren, i, source);\n      result.set(key, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members: new Map(),\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  MergeMember,\n  DeepMergeSymbol,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst KOTLIN_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string_literal'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['interpolated_expression'],\n};\n\nfunction extractDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'class_declaration') {\n    // Handles class, data class, enum class, etc.\n    const nameNode = node.children.find((c) => c.type === 'type_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'function_declaration') {\n    const nameNode = node.children.find((c) => c.type === 'simple_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'object_declaration') {\n    const nameNode = node.children.find((c) => c.type === 'type_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'type_alias') {\n    const nameNode = node.children.find((c) => c.type === 'type_identifier');\n    return nameNode?.text ?? null;\n  }\n  if (node.type === 'property_declaration') {\n    const nameNode = node.children.find((c) => c.type === 'variable_declaration');\n    if (nameNode) {\n      const id = nameNode.children.find((c) => c.type === 'simple_identifier');\n      return id?.text ?? null;\n    }\n  }\n  return null;\n}\n\nfunction findPrecedingKdoc(children: Parser.SyntaxNode[], index: number, source: string): DocstringInfo | null {\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'multiline_comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('/**')) {\n        return { text, startIndex: prev.startIndex, endIndex: prev.endIndex };\n      }\n      return null;\n    }\n    if (prev.type === 'line_comment') continue;\n    return null;\n  }\n  return null;\n}\n\nfunction extractKotlinClassMembers(classBody: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  const children = classBody.namedChildren;\n\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    // The getter/setter fold below advances `i` past sibling accessor nodes, so\n    // remember where the declaration itself sits — the KDoc scan walks backwards\n    // from here and would otherwise start on the declaration (or its getter) and\n    // never reach the doc comment.\n    const declIndex = i;\n    let memberName: string | null = null;\n\n    if (child.type === 'property_declaration') {\n      const varDecl = child.children.find((c) => c.type === 'variable_declaration');\n      memberName = varDecl?.children.find((c) => c.type === 'simple_identifier')?.text ?? null;\n    } else if (child.type === 'function_declaration') {\n      memberName = child.children.find((c) => c.type === 'simple_identifier')?.text ?? null;\n    } else if (child.type === 'companion_object') {\n      memberName = 'companion';\n    }\n\n    if (!memberName) continue;\n\n    // Fold trailing getter/setter into the property's text span\n    let endIdx = child.endIndex;\n    if (child.type === 'property_declaration') {\n      while (i + 1 < children.length) {\n        const next = children[i + 1];\n        if (next.type === 'getter' || next.type === 'setter') {\n          endIdx = next.endIndex;\n          i++;\n        } else {\n          break;\n        }\n      }\n    }\n\n    // Include preceding KDoc comment in the text span so deep merge\n    // inserts the member with its documentation intact.\n    let startIdx = child.startIndex;\n    for (let k = declIndex - 1; k >= 0; k--) {\n      const prev = children[k];\n      if (prev.type === 'multiline_comment') {\n        const text = source.slice(prev.startIndex, prev.endIndex);\n        if (text.startsWith('/**')) startIdx = prev.startIndex;\n        break;\n      }\n      if (prev.type === 'line_comment') continue;\n      break;\n    }\n\n    members.push({ key: memberName, text: source.slice(startIdx, endIdx), startIndex: startIdx, endIndex: endIdx });\n  }\n\n  return members;\n}\n\n/**\n * KDoc signature that identifies a generator-emitted service accessor inside\n * a Kotlin client class. The Kotlin client emitter writes every accessor with this\n * exact doc preamble — when the existing file carries a member with this doc\n * but the regenerated content omits it, the member is stale (its mount target\n * was remapped or removed) and gets pruned.\n */\nconst KOTLIN_MANAGED_ACCESSOR_DOC =\n  /\\/\\*\\*[\\s\\S]*?Lazily-constructed \\[[^\\]]+\\] accessor for this \\[[^\\]]+\\] client\\.[\\s\\S]*?\\*\\//;\n\nexport const kotlinMergeAdapter: MergeAdapter = {\n  language: 'kotlin',\n  grammarModule: 'tree-sitter-kotlin',\n  testFilePatterns: [/Test\\.kt$/],\n  urlFingerprintConfig: KOTLIN_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'multiline_comment' || child.type === 'line_comment') continue;\n\n      if (child.type === 'import_list') {\n        const fullText = source.slice(child.startIndex, child.endIndex);\n        importAnchors.push(fullText);\n        for (const imp of child.namedChildren) {\n          if (imp.type === 'import_header') {\n            const text = source.slice(imp.startIndex, imp.endIndex).trim();\n            // Key on the full import path\n            const idNode = imp.children.find((c) => c.type === 'identifier');\n            const key = idNode?.text ?? text;\n            imports.push({ key, text });\n          }\n        }\n        continue;\n      }\n\n      const name = extractDeclarationName(child);\n      statements.push({\n        key: name,\n        kind: name ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  isManagedMember(member) {\n    return KOTLIN_MANAGED_ACCESSOR_DOC.test(member.text);\n  },\n  importedNames(imp) {\n    const path = imp.text.replace(/^import\\s+/, '').trim();\n    const alias = path.match(/\\s+as\\s+([A-Za-z_][A-Za-z0-9_]*)$/);\n    if (alias) return [alias[1]];\n    const last = path.split('.').pop();\n    // Star imports bind every name in the package — nothing single to track.\n    return last && last !== '*' ? [last] : [];\n  },\n  shouldSkipDeepMerge(_symbolName, existingMemberKeys, newMembers) {\n    // Skip if new members reference instance properties that don't exist in the target\n    const newText = newMembers.map((m) => m.text).join('\\n');\n    for (const match of newText.matchAll(/this\\.(\\w+)/g)) {\n      const propName = match[1];\n      if (propName && !existingMemberKeys.has(propName)) return true;\n    }\n    return false;\n  },\n  extractMembers(tree, source) {\n    const result = new Map<string, DeepMergeSymbol>();\n\n    for (const child of tree.rootNode.children) {\n      if (child.type !== 'class_declaration') continue;\n      const nameNode = child.children.find((c) => c.type === 'type_identifier');\n      if (!nameNode) continue;\n      const body = child.children.find((c) => c.type === 'class_body');\n      if (!body) continue;\n\n      const members = extractKotlinClassMembers(body, source);\n      const firstMember = body.firstNamedChild;\n      const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n      result.set(nameNode.text, { members, bodyEndLine: body.endPosition.row, memberIndent });\n    }\n\n    return result;\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractDeclarationName(child);\n      if (!name) continue;\n\n      const docstring = findPrecedingKdoc(rootChildren, i, source);\n      const members = new Map<string, MemberDocstrings>();\n\n      // Extract member docstrings for classes\n      if (child.type === 'class_declaration') {\n        const body = child.children.find((c) => c.type === 'class_body' || c.type === 'enum_class_body');\n        if (body) {\n          const bodyChildren = body.children;\n          for (let j = 0; j < bodyChildren.length; j++) {\n            const member = bodyChildren[j];\n            const memberName = extractDeclarationName(member);\n            if (!memberName) continue;\n            const memberDoc = findPrecedingKdoc(bodyChildren, j, source);\n            members.set(memberName, {\n              docstring: memberDoc,\n              declStartIndex: member.startIndex,\n              declColumn: member.startPosition.column,\n              urlFingerprint: extractUrlFingerprint(member, KOTLIN_URL_FINGERPRINT_CONFIG),\n            });\n          }\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport { normalizeJsExtension } from '../../utils/naming.js';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DeepMergeSymbol,\n  MergeMember,\n  DocstringInfo,\n  SymbolDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst REEXPORT_PREFIX = '__export:';\n\nfunction extractDeclName(node: Parser.SyntaxNode): string | null {\n  const nameNode = node.childForFieldName('name');\n  if (nameNode) return nameNode.text;\n\n  if (node.type === 'lexical_declaration') {\n    const declarator = node.firstNamedChild;\n    if (declarator?.type === 'variable_declarator') {\n      const name = declarator.childForFieldName('name');\n      if (name) return name.text;\n    }\n  }\n\n  return null;\n}\n\nfunction extractNodeKey(node: Parser.SyntaxNode): { key: string | null; kind: MergeStatement['kind'] } {\n  if (node.type === 'export_statement') {\n    const decl = node.childForFieldName('declaration');\n    if (decl) {\n      return { key: extractDeclName(decl), kind: 'declaration' };\n    }\n\n    const source = node.childForFieldName('source');\n    if (source) {\n      return { key: `${REEXPORT_PREFIX}${normalizeJsExtension(source.text)}`, kind: 'reexport' };\n    }\n\n    return { key: null, kind: 'other' };\n  }\n  return { key: extractDeclName(node), kind: extractDeclName(node) ? 'declaration' : 'other' };\n}\n\nfunction extractClassMembers(classBody: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  for (const child of classBody.namedChildren) {\n    if (child.type === 'method_definition') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode && nameNode.text !== 'constructor') {\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, child.endIndex) });\n      }\n    } else if (child.type === 'public_field_definition') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) {\n        // tree-sitter may exclude the trailing semicolon from\n        // public_field_definition nodes — include it if present\n        let endIdx = child.endIndex;\n        if (source[endIdx] === ';') {\n          endIdx += 1;\n        }\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, endIdx) });\n      }\n    }\n  }\n  return members;\n}\n\nfunction extractInterfaceMembers(body: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  for (const child of body.namedChildren) {\n    if (child.type === 'property_signature' || child.type === 'method_signature') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) {\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, child.endIndex) });\n      }\n    }\n  }\n  return members;\n}\n\nfunction extractEnumMembers(body: Parser.SyntaxNode, source: string): MergeMember[] {\n  const members: MergeMember[] = [];\n  for (const child of body.namedChildren) {\n    if (child.type === 'enum_assignment') {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) {\n        members.push({ key: nameNode.text, text: source.slice(child.startIndex, child.endIndex) });\n      }\n    } else if (child.type === 'property_identifier') {\n      members.push({ key: child.text, text: source.slice(child.startIndex, child.endIndex) });\n    }\n  }\n  return members;\n}\n\nfunction isCommentNode(node: Parser.SyntaxNode): boolean {\n  // tree-sitter extras (comments) may report the parent node's type\n  // instead of 'comment' — check grammarType as fallback\n  return node.type === 'comment' || (node as any).grammarType === 'comment';\n}\n\nfunction findPrecedingDocstring(children: Parser.SyntaxNode[], index: number, source: string): DocstringInfo | null {\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (isCommentNode(prev)) {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('/**')) {\n        return { text, startIndex: prev.startIndex, endIndex: prev.endIndex };\n      }\n      return null;\n    }\n    if (prev.type === ',' || prev.type === ';' || prev.type === '{') continue;\n    return null;\n  }\n  return null;\n}\n\nconst CLASS_MEMBER_TYPES = new Set(['method_definition', 'public_field_definition']);\nconst INTERFACE_MEMBER_TYPES = new Set(['property_signature', 'method_signature']);\nconst ENUM_MEMBER_TYPES = new Set(['enum_assignment', 'property_identifier']);\n\nconst NODE_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string', 'template_string'],\n  contentNodeTypes: ['string_fragment'],\n  interpolationNodeTypes: ['template_substitution'],\n};\n\nfunction extractBodyMemberDocstrings(\n  body: Parser.SyntaxNode,\n  source: string,\n  memberTypes: Set<string>,\n): Map<\n  string,\n  { docstring: DocstringInfo | null; declStartIndex: number; declColumn: number; urlFingerprint?: string }\n> {\n  const result = new Map<\n    string,\n    { docstring: DocstringInfo | null; declStartIndex: number; declColumn: number; urlFingerprint?: string }\n  >();\n  const allChildren = body.children;\n  for (let i = 0; i < allChildren.length; i++) {\n    const child = allChildren[i];\n    if (!memberTypes.has(child.type)) continue;\n    let memberName: string | null = null;\n    if (child.type === 'property_identifier') {\n      memberName = child.text;\n    } else {\n      const nameNode = child.childForFieldName('name');\n      if (nameNode) memberName = nameNode.text;\n    }\n    if (!memberName || memberName === 'constructor') continue;\n    const docstring = findPrecedingDocstring(allChildren, i, source);\n    const fp = extractUrlFingerprint(child, NODE_URL_FINGERPRINT_CONFIG);\n    result.set(memberName, {\n      docstring,\n      declStartIndex: child.startIndex,\n      declColumn: child.startPosition.column,\n      urlFingerprint: fp,\n    });\n  }\n  return result;\n}\n\nexport const nodeMergeAdapter: MergeAdapter = {\n  language: 'node',\n  grammarModule: 'tree-sitter-typescript/bindings/node/typescript.js',\n  normalizeReexport: normalizeJsExtension,\n  testFilePatterns: [/\\.(spec|test)\\.[jt]sx?$/],\n  urlFingerprintConfig: NODE_URL_FINGERPRINT_CONFIG,\n  shouldSkipDeepMerge(_symbolName, existingMemberKeys, newMembers) {\n    // If new members reference instance properties (this.X) that don't exist\n    // in the target class, the merged code would be broken.\n    const newText = newMembers.map((m) => m.text).join('\\n');\n    for (const match of newText.matchAll(/this\\.(\\w+)/g)) {\n      const propName = match[1];\n      if (propName && !existingMemberKeys.has(propName)) {\n        return true;\n      }\n    }\n    return false;\n  },\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'import_statement') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        // Key on module path so `import { X }` and `import type { X }` from\n        // the same module are treated as duplicates\n        const sourceNode = child.childForFieldName('source');\n        const modulePath = sourceNode ? normalizeJsExtension(sourceNode.text) : normalizeJsExtension(text.trim());\n        imports.push({ key: modulePath, text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const { key, kind } = extractNodeKey(child);\n      statements.push({\n        key,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractMembers(tree, source) {\n    const result = new Map<string, DeepMergeSymbol>();\n\n    for (const child of tree.rootNode.children) {\n      if (child.type !== 'export_statement') continue;\n      const decl = child.childForFieldName('declaration');\n      if (!decl) continue;\n\n      const nameNode = decl.childForFieldName('name');\n      if (!nameNode) continue;\n      const symbolName = nameNode.text;\n\n      if (decl.type === 'class_declaration') {\n        const body = decl.childForFieldName('body');\n        if (!body) continue;\n        const members = extractClassMembers(body, source);\n        const firstMember = body.firstNamedChild;\n        const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n        result.set(symbolName, { members, bodyEndLine: body.endPosition.row, memberIndent });\n      } else if (decl.type === 'interface_declaration') {\n        const body = decl.childForFieldName('body');\n        if (!body) continue;\n        const members = extractInterfaceMembers(body, source);\n        const firstMember = body.firstNamedChild;\n        const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n        result.set(symbolName, { members, bodyEndLine: body.endPosition.row, memberIndent });\n      } else if (decl.type === 'enum_declaration') {\n        const body = decl.childForFieldName('body');\n        if (!body) continue;\n        const members = extractEnumMembers(body, source);\n        const firstMember = body.firstNamedChild;\n        const memberIndent = firstMember ? ' '.repeat(firstMember.startPosition.column) : undefined;\n        result.set(symbolName, { members, bodyEndLine: body.endPosition.row, memberIndent });\n      }\n    }\n\n    return result;\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      if (child.type !== 'export_statement') continue;\n      const decl = child.childForFieldName('declaration');\n      if (!decl) continue;\n      const nameNode = decl.childForFieldName('name');\n      if (!nameNode) continue;\n\n      // Find preceding JSDoc for this top-level symbol\n      const docstring = findPrecedingDocstring(rootChildren, i, source);\n\n      // Extract member-level docstrings\n      let members = new Map<string, { docstring: DocstringInfo | null; declStartIndex: number; declColumn: number }>();\n      const body = decl.childForFieldName('body');\n      if (body) {\n        if (decl.type === 'class_declaration') {\n          members = extractBodyMemberDocstrings(body, source, CLASS_MEMBER_TYPES);\n        } else if (decl.type === 'interface_declaration') {\n          members = extractBodyMemberDocstrings(body, source, INTERFACE_MEMBER_TYPES);\n        } else if (decl.type === 'enum_declaration') {\n          members = extractBodyMemberDocstrings(body, source, ENUM_MEMBER_TYPES);\n        }\n      }\n\n      result.set(nameNode.text, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst PHP_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['encapsed_string', 'string'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['variable_name'],\n};\n\nfunction extractPhpDeclarationName(node: Parser.SyntaxNode): string | null {\n  switch (node.type) {\n    case 'class_declaration':\n    case 'interface_declaration':\n    case 'trait_declaration':\n    case 'enum_declaration':\n    case 'function_definition': {\n      const nameNode = node.childForFieldName('name');\n      return nameNode?.text ?? null;\n    }\n    case 'namespace_definition': {\n      const nameNode = node.childForFieldName('name');\n      return nameNode ? `__namespace:${nameNode.text}` : '__namespace:';\n    }\n    default:\n      return null;\n  }\n}\n\nfunction findPhpDocstring(children: Parser.SyntaxNode[], index: number, source: string): DocstringInfo | null {\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('/**')) {\n        return { text, startIndex: prev.startIndex, endIndex: prev.endIndex };\n      }\n      return null;\n    }\n    if (prev.type === ';' || prev.type === '{') continue;\n    return null;\n  }\n  return null;\n}\n\nexport const phpMergeAdapter: MergeAdapter = {\n  language: 'php',\n  grammarModule: 'tree-sitter-php',\n  testFilePatterns: [/Test\\.php$/],\n  urlFingerprintConfig: PHP_URL_FINGERPRINT_CONFIG,\n  resolveGrammar: (mod) => {\n    // ESM import wraps in { default: { php, php_only } }\n    const m = (mod as Record<string, unknown>)?.default ?? mod;\n    if (typeof m === 'object' && m !== null && 'php' in (m as Record<string, unknown>))\n      return (m as { php: unknown }).php;\n    return m;\n  },\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    let importInsertionAnchor: string | undefined;\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'namespace_definition') {\n        importInsertionAnchor = source.slice(child.startIndex, child.endIndex);\n      }\n\n      if (child.type === 'namespace_use_declaration') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const declarationName = extractPhpDeclarationName(child);\n      const kind: MergeStatement['kind'] = declarationName ? 'declaration' : 'other';\n\n      statements.push({\n        key: declarationName,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, importInsertionAnchor, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractPhpDeclarationName(child);\n      if (!name || name.startsWith('__namespace:')) continue;\n\n      const docstring = findPhpDocstring(rootChildren, i, source);\n      const members = new Map<string, MemberDocstrings>();\n\n      const body = child.childForFieldName('body');\n      if (body) {\n        const bodyChildren = body.children;\n        for (let j = 0; j < bodyChildren.length; j++) {\n          const member = bodyChildren[j];\n          if (member.type !== 'method_declaration') continue;\n          const memberName = member.childForFieldName('name')?.text;\n          if (!memberName) continue;\n          const memberDoc = findPhpDocstring(bodyChildren, j, source);\n          members.set(memberName, {\n            docstring: memberDoc,\n            declStartIndex: member.startIndex,\n            declColumn: member.startPosition.column,\n            urlFingerprint: extractUrlFingerprint(member, PHP_URL_FINGERPRINT_CONFIG),\n          });\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst PYTHON_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nfunction extractPythonDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'class_definition' || node.type === 'function_definition') {\n    const nameNode = node.childForFieldName('name');\n    return nameNode?.text ?? null;\n  }\n\n  // Detect `__all__ = [...]` assignments so they get a key and can be deduplicated\n  if (node.type === 'expression_statement') {\n    const firstChild = node.firstNamedChild;\n    if (firstChild?.type === 'assignment') {\n      const left = firstChild.childForFieldName('left');\n      if (left?.type === 'identifier' && left.text === '__all__') {\n        return '__all__';\n      }\n    }\n  }\n\n  return null;\n}\n\nfunction extractPythonDocstring(bodyNode: Parser.SyntaxNode, source: string): DocstringInfo | null {\n  // Python docstrings are the first expression_statement in a body block\n  // where the expression is a string literal\n  for (const child of bodyNode.namedChildren) {\n    if (child.type === 'expression_statement') {\n      const expr = child.firstNamedChild;\n      if (expr?.type === 'string') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        return { text, startIndex: child.startIndex, endIndex: child.endIndex };\n      }\n    }\n    // Only the FIRST statement can be a docstring\n    break;\n  }\n  return null;\n}\n\nfunction collectPrecedingPythonComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'comment') {\n      if (lastIdx === -1) lastIdx = k;\n      firstIdx = k;\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const pythonMergeAdapter: MergeAdapter = {\n  language: 'python',\n  grammarModule: 'tree-sitter-python',\n  testFilePatterns: [/(?:^|\\/)test_.*\\.py$/, /_test\\.py$/],\n  urlFingerprintConfig: PYTHON_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'import_statement' || child.type === 'import_from_statement') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const declarationName = extractPythonDeclarationName(child);\n      const kind: MergeStatement['kind'] = declarationName ? 'declaration' : 'other';\n\n      statements.push({\n        key: declarationName,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractPythonDeclarationName(child);\n      if (!name) continue;\n\n      // Python: class/function docstrings are inside the body, OR use # comments before\n      let docstring: DocstringInfo | null = null;\n      const body = child.childForFieldName('body');\n      if (body) {\n        docstring = extractPythonDocstring(body, source);\n      }\n      // Fallback: check for # comments before the declaration\n      if (!docstring) {\n        docstring = collectPrecedingPythonComments(rootChildren, i, source);\n      }\n\n      const members = new Map<string, MemberDocstrings>();\n\n      // Extract method docstrings for classes\n      if (child.type === 'class_definition' && body) {\n        for (const member of body.namedChildren) {\n          if (member.type !== 'function_definition') continue;\n          const memberName = member.childForFieldName('name')?.text;\n          if (!memberName) continue;\n\n          let memberDoc: DocstringInfo | null = null;\n          const memberBody = member.childForFieldName('body');\n          if (memberBody) {\n            memberDoc = extractPythonDocstring(memberBody, source);\n          }\n\n          members.set(memberName, {\n            docstring: memberDoc,\n            declStartIndex: member.startIndex,\n            declColumn: member.startPosition.column,\n            urlFingerprint: extractUrlFingerprint(member, PYTHON_URL_FINGERPRINT_CONFIG),\n          });\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type {\n  MergeAdapter,\n  MergeStatement,\n  MergeImport,\n  DocstringInfo,\n  SymbolDocstrings,\n  MemberDocstrings,\n} from './types.js';\nimport { extractUrlFingerprint } from './url-fingerprint.js';\n\nconst RUBY_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: ['interpolation'],\n};\n\nfunction isRequireCall(node: Parser.SyntaxNode): boolean {\n  if (node.type !== 'call') return false;\n  const method = node.childForFieldName('method');\n  if (!method) return false;\n  return method.text === 'require' || method.text === 'require_relative';\n}\n\nfunction extractRubyDeclarationName(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'class' && node.type !== 'module') return null;\n  const nameNode = node.childForFieldName('name');\n  return nameNode?.text ?? null;\n}\n\nfunction collectPrecedingRubyComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    const nodeType = (prev as any).grammarType ?? prev.type;\n    if (nodeType === 'comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('#')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const rubyMergeAdapter: MergeAdapter = {\n  language: 'ruby',\n  grammarModule: 'tree-sitter-ruby',\n  testFilePatterns: [/_test\\.rb$/, /_spec\\.rb$/],\n  urlFingerprintConfig: RUBY_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      const declarationName = extractRubyDeclarationName(child);\n      if (isRequireCall(child)) {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const kind: MergeStatement['kind'] = declarationName ? 'declaration' : 'other';\n\n      statements.push({\n        key: declarationName,\n        kind,\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const name = extractRubyDeclarationName(child);\n      if (!name) continue;\n\n      const docstring = collectPrecedingRubyComments(rootChildren, i, source);\n      const members = new Map<string, MemberDocstrings>();\n\n      // Ruby class/module bodies: comments may appear in class children\n      // (before body_statement) or in body_statement children (between methods)\n      if (child.type === 'class' || child.type === 'module') {\n        const allClassChildren = child.children;\n        const body = child.childForFieldName('body');\n\n        // Check for comment before body_statement in class children\n        // (docstring for the first method)\n        let firstMethodDocFromClass: DocstringInfo | null = null;\n        for (let j = 0; j < allClassChildren.length; j++) {\n          if (allClassChildren[j] === body || allClassChildren[j].type === 'body_statement') {\n            firstMethodDocFromClass = collectPrecedingRubyComments(allClassChildren, j, source);\n            break;\n          }\n        }\n\n        if (body) {\n          const bodyChildren = body.children;\n          let firstMethodHandled = false;\n          for (let j = 0; j < bodyChildren.length; j++) {\n            const member = bodyChildren[j];\n            if (member.type !== 'method') continue;\n            const memberName = member.childForFieldName('name')?.text;\n            if (!memberName) continue;\n\n            let memberDoc: DocstringInfo | null;\n            if (!firstMethodHandled && firstMethodDocFromClass) {\n              memberDoc = firstMethodDocFromClass;\n              firstMethodHandled = true;\n            } else {\n              memberDoc = collectPrecedingRubyComments(bodyChildren, j, source);\n              firstMethodHandled = true;\n            }\n\n            members.set(memberName, {\n              docstring: memberDoc,\n              declStartIndex: member.startIndex,\n              declColumn: member.startPosition.column,\n              urlFingerprint: extractUrlFingerprint(member, RUBY_URL_FINGERPRINT_CONFIG),\n            });\n          }\n        }\n      }\n\n      result.set(name, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members,\n      });\n    }\n\n    return result;\n  },\n};\n","import type Parser from 'tree-sitter';\nimport type { MergeAdapter, MergeStatement, MergeImport, DocstringInfo, SymbolDocstrings } from './types.js';\n\nconst RUST_URL_FINGERPRINT_CONFIG = {\n  stringNodeTypes: ['string_literal'],\n  contentNodeTypes: ['string_content'],\n  interpolationNodeTypes: [],\n};\n\nfunction declarationKey(node: Parser.SyntaxNode): string | null {\n  switch (node.type) {\n    case 'struct_item':\n    case 'enum_item':\n    case 'function_item':\n    case 'trait_item':\n    case 'type_item':\n    case 'const_item': {\n      return node.childForFieldName('name')?.text ?? null;\n    }\n    case 'impl_item': {\n      const typeName = node.childForFieldName('type')?.text ?? 'unknown';\n      const traitName = node.childForFieldName('trait')?.text;\n      return traitName ? `impl:${traitName}->${typeName}` : `impl:${typeName}`;\n    }\n    default:\n      return null;\n  }\n}\n\nfunction collectPrecedingRustDocComments(\n  children: Parser.SyntaxNode[],\n  index: number,\n  source: string,\n): DocstringInfo | null {\n  let lastIdx = -1;\n  let firstIdx = -1;\n  for (let k = index - 1; k >= 0; k--) {\n    const prev = children[k];\n    if (prev.type === 'line_comment') {\n      const text = source.slice(prev.startIndex, prev.endIndex);\n      if (text.startsWith('///')) {\n        if (lastIdx === -1) lastIdx = k;\n        firstIdx = k;\n      } else {\n        break;\n      }\n    } else {\n      break;\n    }\n  }\n  if (firstIdx === -1) return null;\n  const first = children[firstIdx];\n  const last = children[lastIdx];\n  return { text: source.slice(first.startIndex, last.endIndex), startIndex: first.startIndex, endIndex: last.endIndex };\n}\n\nexport const rustMergeAdapter: MergeAdapter = {\n  language: 'rust',\n  grammarModule: 'tree-sitter-rust',\n  testFilePatterns: [/_test\\.rs$/, /(?:^|\\/)tests\\/.*\\.rs$/],\n  urlFingerprintConfig: RUST_URL_FINGERPRINT_CONFIG,\n  parseStatements(tree, source) {\n    const imports: MergeImport[] = [];\n    const importAnchors: string[] = [];\n    const statements: MergeStatement[] = [];\n\n    for (const child of tree.rootNode.children) {\n      if (child.type === 'comment') continue;\n\n      if (child.type === 'use_declaration') {\n        const text = source.slice(child.startIndex, child.endIndex);\n        imports.push({ key: text.trim(), text });\n        importAnchors.push(text);\n        continue;\n      }\n\n      const key = declarationKey(child);\n      statements.push({\n        key,\n        kind: key ? 'declaration' : 'other',\n        text: source.slice(child.startIndex, child.endIndex),\n      });\n    }\n\n    return { imports, importAnchors, statements };\n  },\n  renderImports(imports) {\n    return imports.map((entry) => entry.text);\n  },\n  extractDocstrings(tree, source) {\n    const result = new Map<string, SymbolDocstrings>();\n    const rootChildren = tree.rootNode.children;\n\n    for (let i = 0; i < rootChildren.length; i++) {\n      const child = rootChildren[i];\n      const key = declarationKey(child);\n      if (!key) continue;\n\n      const docstring = collectPrecedingRustDocComments(rootChildren, i, source);\n      result.set(key, {\n        docstring,\n        declStartIndex: child.startIndex,\n        declColumn: child.startPosition.column,\n        members: new Map(),\n      });\n    }\n\n    return result;\n  },\n};\n","import type { MergeAdapter } from './types.js';\nimport { dotnetMergeAdapter } from './dotnet.js';\nimport { elixirMergeAdapter } from './elixir.js';\nimport { goMergeAdapter } from './go.js';\nimport { kotlinMergeAdapter } from './kotlin.js';\nimport { nodeMergeAdapter } from './node.js';\nimport { phpMergeAdapter } from './php.js';\nimport { pythonMergeAdapter } from './python.js';\nimport { rubyMergeAdapter } from './ruby.js';\nimport { rustMergeAdapter } from './rust.js';\n\nconst adapters = new Map<string, MergeAdapter>([\n  ['dotnet', dotnetMergeAdapter],\n  ['elixir', elixirMergeAdapter],\n  ['go', goMergeAdapter],\n  ['kotlin', kotlinMergeAdapter],\n  ['node', nodeMergeAdapter],\n  ['php', phpMergeAdapter],\n  ['python', pythonMergeAdapter],\n  ['ruby', rubyMergeAdapter],\n  ['rust', rustMergeAdapter],\n]);\n\nexport function getMergeAdapter(language: string): MergeAdapter | undefined {\n  return adapters.get(language);\n}\n","/**\n * AST-level file merger using tree-sitter.\n *\n * When generating into a directory that already contains files, the merger\n * parses both the existing and generated content, detects top-level symbols,\n * and only appends symbols that don't already exist. Hand-written code is\n * never modified or removed.\n *\n * Supports any language with a tree-sitter grammar package.\n */\n\nimport Parser from 'tree-sitter';\nimport { getMergeAdapter } from './merge-adapters/index.js';\nimport type { MergeImport, ParsedMergeFile, SymbolDocstrings, UrlFingerprintConfig } from './merge-adapters/types.js';\n\n// Cache parser instances per language\nconst parserCache = new Map<string, Parser>();\n\nimport { safeParse } from '../utils/tree-sitter.js';\n\n// --- @deprecated preservation ---\n\n/**\n * When replacing an existing docstring with a generated one, carry over any\n * `@deprecated` lines from the existing doc that aren't present in the\n * generated doc.  This prevents hand-written deprecation notices from being\n * silently dropped during docstring refresh.\n */\nfunction preserveDeprecatedTags(existingDoc: string, generatedDoc: string): string {\n  // Check if the existing docstring contains @deprecated anywhere\n  if (!existingDoc.includes('@deprecated')) return generatedDoc;\n\n  // If generated doc already has @deprecated, no need to merge\n  if (generatedDoc.includes('@deprecated')) return generatedDoc;\n\n  // Extract the @deprecated content from the existing doc.\n  // Handle both multi-line (`* @deprecated ...`) and one-liner (`/** @deprecated ... */`) formats.\n  const deprecatedParts: string[] = [];\n  for (const line of existingDoc.split('\\n')) {\n    if (/@deprecated\\b/.test(line)) {\n      // Normalize to JSDoc member format: `   * @deprecated ...`\n      const match = line.match(/@deprecated\\b.*/);\n      if (match) {\n        // Strip trailing */ and whitespace (from one-liner JSDoc like `/** @deprecated ... */`)\n        const cleaned = match[0].replace(/\\s*\\*\\/\\s*$/, '');\n        deprecatedParts.push(`   * ${cleaned}`);\n      }\n    }\n  }\n  if (deprecatedParts.length === 0) return generatedDoc;\n\n  // Insert @deprecated lines before the closing */ of the generated doc\n  const closingIdx = generatedDoc.lastIndexOf('*/');\n  if (closingIdx === -1) return generatedDoc;\n  const before = generatedDoc.slice(0, closingIdx);\n  const after = generatedDoc.slice(closingIdx);\n  return before + deprecatedParts.join('\\n') + '\\n ' + after;\n}\n\n// --- @oagen-ignore region helpers ---\n\ninterface IgnoredRegion {\n  startIndex: number;\n  endIndex: number;\n}\n\nfunction findIgnoredRegions(source: string): IgnoredRegion[] {\n  const regions: IgnoredRegion[] = [];\n  const startTag = '@oagen-ignore-start';\n  const endTag = '@oagen-ignore-end';\n  let searchFrom = 0;\n\n  while (true) {\n    const startIdx = source.indexOf(startTag, searchFrom);\n    if (startIdx === -1) break;\n    const endIdx = source.indexOf(endTag, startIdx + startTag.length);\n    if (endIdx === -1) break; // Unclosed — silently ignore\n    regions.push({ startIndex: startIdx, endIndex: endIdx + endTag.length });\n    searchFrom = endIdx + endTag.length;\n  }\n\n  return regions;\n}\n\nfunction buildIgnoredSymbolNames(docstrings: Map<string, SymbolDocstrings>, regions: IgnoredRegion[]): Set<string> {\n  if (regions.length === 0) return new Set();\n  const ignored = new Set<string>();\n  for (const [name, info] of docstrings) {\n    if (regions.some((r) => info.declStartIndex >= r.startIndex && info.declStartIndex <= r.endIndex)) {\n      ignored.add(name);\n    }\n  }\n  return ignored;\n}\n\nfunction clampIndex(value: number, contentLength: number): number {\n  if (!Number.isFinite(value)) return 0;\n  if (value < 0) return 0;\n  if (value > contentLength) return contentLength;\n  return value;\n}\n\n/**\n * Resolve the declaration line start for insertion using the current content,\n * instead of relying on parser column arithmetic. This avoids misplaced inserts\n * when parser columns/offsets drift.\n */\nfunction declarationLineStart(content: string, declStartIndex: number): number {\n  const idx = clampIndex(declStartIndex, content.length);\n  const prevNewline = content.lastIndexOf('\\n', Math.max(0, idx - 1));\n  return prevNewline === -1 ? 0 : prevNewline + 1;\n}\n\n// --- stale managed-member pruning helpers ---\n\n/**\n * Widen a member's byte range so deleting it removes whole lines.\n *\n * The raw range starts at the declaration (or its docstring), which sits after\n * the member's indentation — splicing it out verbatim leaves that indentation\n * glued to the following line. Extends backwards over the indentation and\n * forwards over the trailing newline, then absorbs the blank line the removal\n * would otherwise duplicate (or strand in front of the block's closing brace).\n */\nfunction expandPruneRange(source: string, rawStart: number, rawEnd: number): { start: number; end: number } {\n  let start = rawStart;\n  while (start > 0 && (source[start - 1] === ' ' || source[start - 1] === '\\t')) start--;\n\n  let end = rawEnd;\n  while (end < source.length && (source[end] === ' ' || source[end] === '\\t')) end++;\n  end = skipLineBreak(source, end);\n\n  if (precededByBlankLine(source, start)) {\n    if (startsWithLineBreak(source, end)) {\n      // Blank line on both sides — keep one.\n      end = skipLineBreak(source, end);\n    } else if (/^[ \\t]*\\}/.test(source.slice(end, end + 40))) {\n      // Last member in the block — don't leave the closing brace on its own\n      // after a blank line.\n      start = backOverLineBreak(source, start);\n    }\n  }\n\n  return { start, end };\n}\n\n// Line-break helpers below treat CRLF as one terminator: an SDK checked out with\n// `core.autocrlf` on would otherwise leave a stray `\\r` line behind every prune.\n\nfunction startsWithLineBreak(source: string, idx: number): boolean {\n  return source[idx] === '\\n' || (source[idx] === '\\r' && source[idx + 1] === '\\n');\n}\n\nfunction skipLineBreak(source: string, idx: number): number {\n  let i = idx;\n  if (source[i] === '\\r') i++;\n  return source[i] === '\\n' ? i + 1 : i;\n}\n\nfunction backOverLineBreak(source: string, idx: number): number {\n  let i = idx;\n  if (source[i - 1] === '\\n') i--;\n  if (source[i - 1] === '\\r') i--;\n  return i;\n}\n\n/** Whether the line ending immediately before `idx` (a line start) is empty. */\nfunction precededByBlankLine(source: string, idx: number): boolean {\n  if (idx === 0 || source[idx - 1] !== '\\n') return false;\n  const priorLineEnd = backOverLineBreak(source, idx);\n  return priorLineEnd > 0 && source[priorLineEnd - 1] === '\\n';\n}\n\nfunction referencesIdentifier(source: string, name: string): boolean {\n  return new RegExp(`\\\\b${name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(source);\n}\n\n/**\n * Blank out comments and string text, preserving offsets and line structure.\n *\n * An identifier lookup over raw source can't tell a live reference from a name\n * that merely survives in prose. That distinction decides whether an import\n * stays: keeping one whose only remaining mention is a KDoc leaves an import of\n * a class the generator no longer emits, which doesn't compile — the very\n * failure the prune exists to prevent.\n *\n * Interpolated expressions are the exception: `\"${Agents.NAME}\"` is code that\n * sits inside a string literal, and masking it would drop an import the file\n * genuinely uses. String extents are masked around those holes, not over them.\n *\n * Grammar node names come from the adapter's `urlFingerprintConfig`, which\n * already inventories exactly these three categories per language. Comments are\n * matched structurally instead — every grammar we support names them `*comment`.\n */\nfunction maskNonCode(tree: Parser.Tree, source: string, config: UrlFingerprintConfig | undefined): string {\n  const stringNodeTypes = new Set(config?.stringNodeTypes ?? []);\n  const interpolationNodeTypes = new Set(config?.interpolationNodeTypes ?? []);\n\n  const spans: [number, number][] = [];\n  const collectStringSpans = (node: Parser.SyntaxNode): void => {\n    // Everything in the literal is prose except the interpolation holes.\n    const holes: [number, number][] = [];\n    const findHoles = (n: Parser.SyntaxNode): void => {\n      if (interpolationNodeTypes.has(n.type)) {\n        holes.push([n.startIndex, n.endIndex]);\n        return;\n      }\n      for (const child of n.children) findHoles(child);\n    };\n    findHoles(node);\n\n    let cursor = node.startIndex;\n    for (const [holeStart, holeEnd] of holes) {\n      if (holeStart > cursor) spans.push([cursor, holeStart]);\n      cursor = holeEnd;\n    }\n    if (cursor < node.endIndex) spans.push([cursor, node.endIndex]);\n  };\n\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type.includes('comment')) {\n      spans.push([node.startIndex, node.endIndex]);\n      return;\n    }\n    if (stringNodeTypes.has(node.type)) {\n      collectStringSpans(node);\n      return;\n    }\n    for (const child of node.children) walk(child);\n  };\n  walk(tree.rootNode);\n  if (spans.length === 0) return source;\n\n  let masked = '';\n  let cursor = 0;\n  for (const [spanStart, spanEnd] of spans) {\n    if (spanStart < cursor) continue;\n    masked += source.slice(cursor, spanStart) + source.slice(spanStart, spanEnd).replace(/[^\\r\\n]/g, ' ');\n    cursor = spanEnd;\n  }\n  return masked + source.slice(cursor);\n}\n\nfunction removeLines(source: string, lines: Set<string>): string {\n  return source\n    .split('\\n')\n    .filter((line) => !lines.has(line.trim()))\n    .join('\\n');\n}\n\n/**\n * Resolve a docstring range by searching for the nearest matching text before\n * the declaration start. Falls back to parser-provided offsets when search fails.\n */\nfunction resolveDocRange(\n  content: string,\n  docText: string,\n  declStartIndex: number,\n  fallbackStart: number,\n  fallbackEnd: number,\n): { start: number; end: number } {\n  const safeDecl = clampIndex(declStartIndex, content.length);\n  const safeFallbackStart = clampIndex(fallbackStart, content.length);\n  const safeFallbackEnd = clampIndex(fallbackEnd, content.length);\n  const found = content.lastIndexOf(docText, safeDecl);\n  if (found !== -1) {\n    return { start: found, end: found + docText.length };\n  }\n  return { start: safeFallbackStart, end: safeFallbackEnd };\n}\n\n/**\n * Check if a tree-sitter grammar is configured for the given language.\n */\nexport function hasGrammar(language: string): boolean {\n  return getMergeAdapter(language) !== undefined;\n}\n\nasync function getParser(language: string): Promise<Parser> {\n  const cached = parserCache.get(language);\n  if (cached) return cached;\n\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(\n      `No tree-sitter grammar configured for language \"${language}\". ` +\n        `Add a merge adapter and install the corresponding tree-sitter grammar package.`,\n    );\n  }\n\n  const mod = await import(adapter.grammarModule);\n  const exported = adapter.resolveGrammar ? adapter.resolveGrammar(mod) : mod;\n  const grammar = (exported as { default?: unknown }).default ?? exported;\n  const parser = new Parser();\n  parser.setLanguage(grammar);\n  parserCache.set(language, parser);\n  return parser;\n}\n\ninterface ParsedSymbols {\n  names: Set<string>;\n  /** Trimmed text of unnamed top-level statements (for text-based dedup) */\n  unnamedTexts: Set<string>;\n}\n\n/**\n * Extract all top-level symbol names (and unnamed statement texts) from source code.\n */\nexport async function extractTopLevelSymbols(source: string, language: string): Promise<ParsedSymbols> {\n  const parser = await getParser(language);\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(`No merge adapter configured for language \"${language}\"`);\n  }\n  if (typeof source !== 'string') {\n    throw new Error(`extractTopLevelSymbols: expected string source, got ${typeof source}`);\n  }\n  const tree = safeParse(parser, source);\n  const names = new Set<string>();\n  const unnamedTexts = new Set<string>();\n  const parsed = adapter.parseStatements(tree, source);\n\n  for (const imp of parsed.imports) {\n    names.add(imp.key);\n  }\n  for (const statement of parsed.statements) {\n    if (statement.key) {\n      names.add(statement.key);\n    } else {\n      unnamedTexts.add(statement.text.trim());\n    }\n  }\n\n  return { names, unnamedTexts };\n}\n\n/** Convenience wrapper that returns only the name set. */\nexport async function extractTopLevelNames(source: string, language: string): Promise<Set<string>> {\n  return (await extractTopLevelSymbols(source, language)).names;\n}\n\n/**\n * Extract top-level statements from generated source with their names\n * and exact text span.\n */\nexport async function extractStatements(source: string, language: string): Promise<ParsedMergeFile> {\n  const parser = await getParser(language);\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(`No merge adapter configured for language \"${language}\"`);\n  }\n  const tree = safeParse(parser, source);\n  return adapter.parseStatements(tree, source);\n}\n\n/**\n * Return a map of top-level class name → { bodyEndLine, bodyEndCol } using\n * tree-sitter.  `bodyEndLine` is 0-based.  For brace-delimited classes the\n * end points at the closing brace line; for indentation-delimited classes\n * it points one past the last line of the class body.\n */\nexport async function extractClassEndLines(\n  source: string,\n  language: string,\n): Promise<Map<string, { bodyEndLine: number }>> {\n  const parser = await getParser(language);\n  const tree = safeParse(parser, source);\n  const map = new Map<string, { bodyEndLine: number }>();\n\n  function processClassNode(node: Parser.SyntaxNode): void {\n    const nameNode =\n      node.childForFieldName('name') ??\n      node.children.find((c) => c.type === 'type_identifier' || c.type === 'identifier');\n    if (!nameNode) return;\n    const name = nameNode.text;\n\n    const body =\n      node.childForFieldName('body') ?? node.children.find((c) => c.type === 'class_body' || c.type === 'body');\n    const endRow = body ? body.endPosition.row : node.endPosition.row;\n    const lastChar = source[body ? body.endIndex - 1 : node.endIndex - 1];\n\n    if (lastChar === '}') {\n      map.set(name, { bodyEndLine: endRow });\n    } else {\n      map.set(name, { bodyEndLine: endRow + 1 });\n    }\n  }\n\n  // Walk the tree recursively. Ruby (and Python) often nest target classes\n  // inside `module Foo` / `class Outer:` containers, so a flat iteration over\n  // root children would miss them.\n  function walk(node: Parser.SyntaxNode): void {\n    if (node.type === 'class' || node.type === 'class_definition' || node.type === 'class_declaration') {\n      processClassNode(node);\n    }\n    if (node.type === 'decorated_definition') {\n      for (const inner of node.namedChildren) {\n        if (inner.type === 'class_definition') processClassNode(inner);\n      }\n    }\n    if (node.type === 'export_statement') {\n      for (const inner of node.namedChildren) {\n        if (inner.type === 'class_declaration') processClassNode(inner);\n      }\n    }\n    for (const child of node.namedChildren) walk(child);\n  }\n  for (const child of tree.rootNode.children) {\n    walk(child);\n  }\n\n  return map;\n}\n\nexport interface MergeResult {\n  content: string;\n  added: number;\n  preserved: number;\n  changed: boolean;\n}\n\n/**\n * Merge generated content into an existing file.\n *\n * - Parses both files with tree-sitter\n * - Detects which top-level symbols already exist\n * - Appends only new symbols\n * - Never modifies or removes existing code\n * - Adds auto-generated header if not present\n */\nexport async function mergeIntoExisting(\n  existingContent: string,\n  generatedContent: string,\n  language: string,\n  header: string,\n): Promise<MergeResult> {\n  const adapter = getMergeAdapter(language);\n  if (!adapter) {\n    throw new Error(`No merge adapter configured for language \"${language}\"`);\n  }\n\n  // Parse existing file once — extract both symbols and statements from the same AST pass\n  const existingStatements = await extractStatements(existingContent, language);\n  const generatedStatements = await extractStatements(generatedContent, language);\n\n  const existingKeys = new Set<string>();\n  const existingUnnamedTexts = new Set<string>();\n  const existingImportKeys = new Set<string>();\n  const existingReexports = new Set<string>();\n  let lastImportEndIndex = -1;\n\n  // Collect import keys AND imported identifiers (to prevent adding declarations\n  // that clash with already-imported names)\n  const existingImportedNames = new Set<string>();\n  for (const imp of existingStatements.imports) {\n    existingImportKeys.add(imp.key);\n    // Extract identifiers from import text: import { Foo, Bar } from '...'\n    const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n    if (braceMatch) {\n      for (const name of braceMatch[1].split(',')) {\n        const trimmed = name.replace(/\\btype\\b/, '').trim();\n        if (trimmed) existingImportedNames.add(trimmed);\n      }\n    }\n  }\n  for (const anchor of existingStatements.importAnchors) {\n    const linesBefore = existingContent.slice(0, existingContent.indexOf(anchor)).split('\\n').length - 1;\n    const stmtLines = anchor.split('\\n').length;\n    lastImportEndIndex = linesBefore + stmtLines - 1;\n  }\n  if (lastImportEndIndex === -1 && existingStatements.importInsertionAnchor) {\n    const linesBefore =\n      existingContent.slice(0, existingContent.indexOf(existingStatements.importInsertionAnchor)).split('\\n').length -\n      1;\n    const stmtLines = existingStatements.importInsertionAnchor.split('\\n').length;\n    lastImportEndIndex = linesBefore + stmtLines - 1;\n  }\n\n  // Track all names exported by existing statements (both direct exports and\n  // re-export aliases like `export { X as Y }`).  Used to prevent the merger\n  // from appending a re-export that introduces a duplicate exported name.\n  const existingExportedNames = new Set<string>();\n\n  for (const stmt of existingStatements.statements) {\n    if (stmt.kind === 'reexport') {\n      existingReexports.add(adapter.normalizeReexport ? adapter.normalizeReexport(stmt.text.trim()) : stmt.text.trim());\n      // Collect aliased export names from re-exports\n      const braceMatch = stmt.text.match(/\\{([^}]+)\\}/);\n      if (braceMatch) {\n        for (const part of braceMatch[1].split(',')) {\n          const segments = part.trim().split(/\\s+as\\s+/);\n          const exportedName = (segments[1] ?? segments[0]).trim();\n          if (exportedName) existingExportedNames.add(exportedName);\n        }\n      }\n    }\n    if (stmt.key) {\n      existingKeys.add(stmt.key);\n      existingExportedNames.add(stmt.key);\n    } else {\n      existingUnnamedTexts.add(stmt.text.trim());\n    }\n  }\n\n  const headerLine = header.trim();\n\n  const newImports: MergeImport[] = [];\n  const toAppend: string[] = [];\n  let preserved = 0;\n\n  for (const imp of generatedStatements.imports) {\n    if (imp.text.trim() === headerLine) continue;\n    if (existingImportKeys.has(imp.key)) {\n      // The existing file already imports from this module path.\n      // Check if the generated import adds identifiers not present in\n      // the existing import — if so, create a supplemental import with\n      // only the new identifiers.  The supplemental participates in the\n      // usage-based filter (below) so unused identifiers are dropped.\n      const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n      if (braceMatch) {\n        const names = braceMatch[1]\n          .split(',')\n          .map((n) => n.replace(/\\btype\\b/, '').trim())\n          .filter(Boolean);\n        const newNames = names.filter((n) => !existingImportedNames.has(n) && !existingKeys.has(n));\n        if (newNames.length > 0) {\n          const isTypeImport = imp.text.trimStart().startsWith('import type');\n          const prefix = isTypeImport ? 'import type' : 'import';\n          const sourceMatch = imp.text.match(/from\\s+(['\"][^'\"]+['\"]);?/);\n          if (sourceMatch) {\n            newImports.push({\n              key: imp.key + '#supplemental',\n              text: `${prefix} { ${newNames.join(', ')} } from ${sourceMatch[1]};`,\n            });\n          }\n        }\n      }\n      preserved++;\n      continue;\n    }\n    // Strip out identifiers that are already imported from another path.\n    // This prevents duplicates when the generated file uses a specific path\n    // (e.g., '../interfaces/organization.interface') while the existing file\n    // imports the same names from a barrel (e.g., '../interfaces').\n    const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n    if (braceMatch) {\n      const names = braceMatch[1]\n        .split(',')\n        .map((n) => n.replace(/\\btype\\b/, '').trim())\n        .filter(Boolean);\n      // Check against both existing imports AND existing top-level declarations\n      const isAlreadyDefined = (n: string) => existingImportedNames.has(n) || existingKeys.has(n);\n      if (names.length > 0 && names.every(isAlreadyDefined)) {\n        preserved++;\n        continue;\n      }\n      // If only SOME identifiers are already defined, strip them out and keep only new ones\n      if (names.some(isAlreadyDefined)) {\n        const newNames = names.filter((n) => !isAlreadyDefined(n));\n        if (newNames.length === 0) {\n          preserved++;\n          continue;\n        }\n        // Rebuild the import with only new identifiers\n        const isTypeImport = imp.text.trimStart().startsWith('import type');\n        const prefix = isTypeImport ? 'import type' : 'import';\n        const sourceMatch = imp.text.match(/from\\s+(['\"][^'\"]+['\"]);?/);\n        if (sourceMatch) {\n          const newText = `${prefix} { ${newNames.join(', ')} } from ${sourceMatch[1]};`;\n          newImports.push({ key: imp.key, text: newText });\n          continue;\n        }\n      }\n    }\n    newImports.push(imp);\n  }\n\n  for (const stmt of generatedStatements.statements) {\n    // Skip the header comment\n    if (stmt.text.trim() === headerLine) continue;\n\n    // Skip re-export statements that duplicate existing re-exports\n    // (e.g., generated uses .js extension but existing doesn't).\n    // Allow genuinely new re-exports through.\n    if (stmt.kind === 'reexport') {\n      const normalizedText = adapter.normalizeReexport ? adapter.normalizeReexport(stmt.text.trim()) : stmt.text.trim();\n      if (existingReexports.has(normalizedText) || (stmt.key !== null && existingKeys.has(stmt.key))) {\n        preserved++;\n        continue;\n      }\n      // Also skip re-exports whose aliased names are already defined as\n      // top-level exports in the existing file (e.g., generated file has\n      // `export { X as deserializeFoo } from '...'` but existing file\n      // already has `export const deserializeFoo = ...`).\n      const braceMatch = stmt.text.match(/\\{([^}]+)\\}/);\n      if (braceMatch) {\n        const exportedNames = braceMatch[1]\n          .split(',')\n          .map((n) => {\n            const parts = n.trim().split(/\\s+as\\s+/);\n            return (parts[1] ?? parts[0]).trim();\n          })\n          .filter(Boolean);\n        if (exportedNames.length > 0 && exportedNames.every((n) => existingExportedNames.has(n))) {\n          preserved++;\n          continue;\n        }\n      }\n    }\n\n    if (stmt.key && (existingKeys.has(stmt.key) || existingImportedNames.has(stmt.key))) {\n      preserved++;\n      continue;\n    }\n\n    if (!stmt.key) {\n      if (existingUnnamedTexts.has(stmt.text.trim())) {\n        preserved++;\n        continue;\n      }\n    }\n\n    toAppend.push(stmt.text);\n  }\n\n  if (newImports.length === 0 && toAppend.length === 0) {\n    // No top-level changes — check for deep merge before returning\n    if (!adapter.extractMembers) {\n      // Still need to check docstring refresh below\n    }\n  }\n\n  let result = existingContent;\n\n  // Append new top-level symbols first (so deep merge can see them)\n  if (toAppend.length > 0) {\n    result = result.trimEnd() + '\\n\\n' + toAppend.join('\\n\\n') + '\\n';\n  }\n\n  // Deep merge pass: add new members to existing symbols\n  // Runs after import/symbol merge so line numbers are based on the updated content\n  let deepAdded = 0;\n  let deepPruned = 0;\n  const insertions: { line: number; text: string }[] = [];\n  const prunedTexts: string[] = [];\n  if (adapter.extractMembers) {\n    const parser = await getParser(language);\n    const resultTree = safeParse(parser, result);\n    const generatedTree = safeParse(parser, generatedContent);\n    const resultSymbols = adapter.extractMembers(resultTree, result);\n    const generatedSymbols = adapter.extractMembers(generatedTree, generatedContent);\n\n    // Build ignored symbol set from @oagen-ignore-start/@oagen-ignore-end regions\n    const existingTree = safeParse(parser, existingContent);\n    const existingDocs = adapter.extractDocstrings(existingTree, existingContent);\n    const deepIgnoredRegions = findIgnoredRegions(existingContent);\n    const deepIgnoredSymbols = buildIgnoredSymbolNames(existingDocs, deepIgnoredRegions);\n\n    // Pass 1: prune stale \"managed\" members (existing members the adapter\n    // recognizes as generator-owned but that no longer appear in the\n    // regenerated content — e.g. accessors whose mount target was remapped).\n    // Done as byte-range deletes before line-based insertions so insertion\n    // line numbers stay valid for the post-prune result.\n    if (adapter.isManagedMember) {\n      const pruneEdits: { start: number; end: number }[] = [];\n      for (const [symbolName, genSymbol] of generatedSymbols) {\n        if (deepIgnoredSymbols.has(symbolName)) continue;\n        const existSymbol = resultSymbols.get(symbolName);\n        if (!existSymbol) continue;\n        const genMemberKeys = new Set(genSymbol.members.map((m) => m.key));\n        for (const existMember of existSymbol.members) {\n          if (genMemberKeys.has(existMember.key)) continue;\n          if (existMember.startIndex === undefined || existMember.endIndex === undefined) continue;\n          if (!adapter.isManagedMember(existMember)) continue;\n          pruneEdits.push({ start: existMember.startIndex, end: existMember.endIndex });\n        }\n      }\n      if (pruneEdits.length > 0) {\n        pruneEdits.sort((a, b) => b.start - a.start);\n        for (const edit of pruneEdits) {\n          const { start, end } = expandPruneRange(result, edit.start, edit.end);\n          prunedTexts.push(result.slice(start, end));\n          result = result.slice(0, start) + result.slice(end);\n        }\n        deepPruned = pruneEdits.length;\n        // Re-extract since byte offsets and line numbers shifted.\n        const reTree = safeParse(parser, result);\n        resultSymbols.clear();\n        for (const [k, v] of adapter.extractMembers(reTree, result)) resultSymbols.set(k, v);\n      }\n    }\n\n    // Pass 2: append new members the regenerated content adds.\n    for (const [symbolName, genSymbol] of generatedSymbols) {\n      if (deepIgnoredSymbols.has(symbolName)) continue;\n      const existSymbol = resultSymbols.get(symbolName);\n      if (!existSymbol) continue; // New symbol — handled by top-level append\n\n      const existingMemberKeys = new Set(existSymbol.members.map((m) => m.key));\n      const newMembers = genSymbol.members.filter((m) => !existingMemberKeys.has(m.key));\n\n      if (newMembers.length > 0) {\n        // Let the adapter decide whether to skip deep merge (e.g., when new members\n        // reference dependencies the existing symbol doesn't provide)\n        if (adapter.shouldSkipDeepMerge?.(symbolName, existingMemberKeys, newMembers)) {\n          continue;\n        }\n\n        const indent = existSymbol.memberIndent ?? '  ';\n        const insertText = newMembers.map((m) => indent + m.text).join('\\n\\n');\n        // Leading blank line separates inserted members from existing ones.\n        insertions.push({ line: existSymbol.bodyEndLine, text: '\\n' + insertText });\n        deepAdded += newMembers.length;\n      }\n    }\n\n    if (insertions.length > 0) {\n      // Apply bottom-up to avoid offset shifting\n      insertions.sort((a, b) => b.line - a.line);\n      const resultLines = result.split('\\n');\n      for (const ins of insertions) {\n        resultLines.splice(ins.line, 0, ins.text);\n      }\n      result = resultLines.join('\\n');\n    }\n  }\n\n  // Insert new imports only when new symbols or members were actually added.\n  // This prevents orphaned imports for generated code that wasn't merged in.\n  // Additionally, filter imports to only include identifiers actually used in the\n  // appended/inserted code — prevents orphaned imports for generated code that\n  // referenced types used in other (non-appended) generated functions.\n  if (newImports.length > 0 && (toAppend.length > 0 || deepAdded > 0)) {\n    // Build text of all new code that was actually added (appended + deep-merged members)\n    const addedParts: string[] = [...toAppend];\n    if (insertions) {\n      for (const ins of insertions) {\n        addedParts.push(ins.text);\n      }\n    }\n    const addedCodeText = addedParts.join('\\n');\n\n    // Filter imports to only identifiers that appear in the added code.\n    // Strip individual unused identifiers from each import rather than\n    // keeping/dropping the entire import — prevents orphaned imports when\n    // a generated import line contains both used and unused identifiers\n    // (e.g., `import { deserializeFoo, serializeFoo }` where only\n    // serializeFoo is used in the appended code).\n    const filteredImports: MergeImport[] = [];\n    for (const imp of newImports) {\n      const braceMatch = imp.text.match(/\\{([^}]+)\\}/);\n      if (!braceMatch) {\n        // Non-destructured import (e.g., default import) — keep as-is\n        filteredImports.push(imp);\n        continue;\n      }\n      const names = braceMatch[1]\n        .split(',')\n        .map((n) => n.replace(/\\btype\\b/, '').trim())\n        .filter(Boolean);\n      const usedNames = names.filter((name) => addedCodeText.includes(name));\n      if (usedNames.length === 0) continue; // Drop entirely\n      if (usedNames.length === names.length) {\n        // All identifiers used — keep original import\n        filteredImports.push(imp);\n      } else {\n        // Rebuild import with only used identifiers\n        const isTypeImport = imp.text.trimStart().startsWith('import type');\n        const prefix = isTypeImport ? 'import type' : 'import';\n        const sourceMatch = imp.text.match(/from\\s+(['\"][^'\"]+['\"]);?/);\n        if (sourceMatch) {\n          filteredImports.push({\n            key: imp.key,\n            text: `${prefix} { ${usedNames.join(', ')} } from ${sourceMatch[1]};`,\n          });\n        } else {\n          filteredImports.push(imp);\n        }\n      }\n    }\n\n    if (filteredImports.length > 0) {\n      const renderedImports = adapter.renderImports\n        ? adapter.renderImports(filteredImports)\n        : filteredImports.map((entry) => entry.text);\n      const lines = result.split('\\n');\n      const insertIdx = lastImportEndIndex + 1;\n      lines.splice(insertIdx, 0, ...renderedImports);\n      result = lines.join('\\n');\n    }\n  }\n\n  // Drop imports the pruned managed members were the last users of. A managed\n  // accessor that leaves the spec takes its service class with it, so keeping\n  // the import is a compile error rather than merely dead code. Runs last so it\n  // sees every insertion — both new members and new imports — and so removing\n  // lines can't shift the line numbers those insertions were computed against.\n  if (prunedTexts.length > 0 && adapter.importedNames) {\n    const prunedText = prunedTexts.join('\\n');\n    // Survival is judged against code only — a class name left behind in a KDoc\n    // is not a use, and treating it as one keeps an unresolvable import.\n    const parser = await getParser(language);\n    const codeOnly = maskNonCode(safeParse(parser, result), result, adapter.urlFingerprintConfig);\n    const orphaned = new Set<string>();\n    for (const imp of existingStatements.imports) {\n      const names = adapter.importedNames(imp);\n      if (names.length === 0) continue;\n      if (!names.some((n) => referencesIdentifier(prunedText, n))) continue;\n      const line = imp.text.trim();\n      const withoutImport = removeLines(codeOnly, new Set([line]));\n      if (names.some((n) => referencesIdentifier(withoutImport, n))) continue;\n      orphaned.add(line);\n    }\n    if (orphaned.size > 0) result = removeLines(result, orphaned);\n  }\n\n  // Docstring refresh pass: update existing docstrings to match generated content\n  let docstringUpdates = 0;\n  {\n    const parser = await getParser(language);\n    const resultTree = safeParse(parser, result);\n    const generatedTree = safeParse(parser, generatedContent);\n    const resultDocs = adapter.extractDocstrings(resultTree, result);\n    const generatedDocs = adapter.extractDocstrings(generatedTree, generatedContent);\n    const docIgnoredRegions = findIgnoredRegions(result);\n    const docIgnoredSymbols = buildIgnoredSymbolNames(resultDocs, docIgnoredRegions);\n\n    const edits: { start: number; end: number; newText: string }[] = [];\n\n    for (const [symbolName, genInfo] of generatedDocs) {\n      const existInfo = resultDocs.get(symbolName);\n      if (!existInfo) continue;\n      if (docIgnoredSymbols.has(symbolName)) continue;\n\n      // Skip header comments being treated as docstrings\n      const genDoc = genInfo.docstring && genInfo.docstring.text.trim() !== headerLine ? genInfo.docstring : null;\n\n      // Top-level docstring\n      if (genDoc) {\n        if (existInfo.docstring) {\n          const isPreserved = existInfo.docstring.text.includes('@oagen-ignore');\n          if (!isPreserved && existInfo.docstring.text !== genDoc.text) {\n            const newText = preserveDeprecatedTags(existInfo.docstring.text, genDoc.text);\n            const range = resolveDocRange(\n              result,\n              existInfo.docstring.text,\n              existInfo.declStartIndex,\n              existInfo.docstring.startIndex,\n              existInfo.docstring.endIndex,\n            );\n            edits.push({\n              start: range.start,\n              end: range.end,\n              newText,\n            });\n            docstringUpdates++;\n          }\n        } else {\n          const lineStart = declarationLineStart(result, existInfo.declStartIndex);\n          const indent = ' '.repeat(existInfo.declColumn);\n          edits.push({\n            start: lineStart,\n            end: lineStart,\n            newText: indent + genDoc.text + '\\n',\n          });\n          docstringUpdates++;\n        }\n      }\n\n      // Member-level docstrings — first pass: match by name\n      const matchedExistMembers = new Set<string>();\n      for (const [memberName, genMember] of genInfo.members) {\n        const existMember = existInfo.members.get(memberName);\n        if (!existMember) continue;\n        matchedExistMembers.add(memberName);\n        if (!genMember.docstring) continue;\n\n        if (existMember.docstring) {\n          const isPreserved = existMember.docstring.text.includes('@oagen-ignore');\n          if (!isPreserved && existMember.docstring.text !== genMember.docstring.text) {\n            const newText = preserveDeprecatedTags(existMember.docstring.text, genMember.docstring.text);\n            const range = resolveDocRange(\n              result,\n              existMember.docstring.text,\n              existMember.declStartIndex,\n              existMember.docstring.startIndex,\n              existMember.docstring.endIndex,\n            );\n            edits.push({\n              start: range.start,\n              end: range.end,\n              newText,\n            });\n            docstringUpdates++;\n          }\n        } else {\n          const lineStart = declarationLineStart(result, existMember.declStartIndex);\n          const indent = ' '.repeat(existMember.declColumn);\n          edits.push({\n            start: lineStart,\n            end: lineStart,\n            newText: indent + genMember.docstring.text + '\\n',\n          });\n          docstringUpdates++;\n        }\n      }\n\n      // Member-level docstrings — second pass: URL fingerprint fallback\n      // Match generated members to existing members by URL pattern when\n      // name-based matching fails (e.g., generated \"find\" vs existing \"getWidget\"\n      // both call this.client.get('/widgets/${id}')).\n      //\n      // Safety: only attempt fingerprint matching when there is exactly ONE\n      // unmatched generated member and ONE unmatched existing member for a\n      // given fingerprint.  When multiple members share the same URL path\n      // (e.g., POST and GET on /authorization/roles), fingerprint matching\n      // is ambiguous and would swap docstrings between methods.\n      const unmatchedGenByFp = new Map<\n        string,\n        { name: string; member: typeof genInfo.members extends Map<string, infer V> ? V : never }[]\n      >();\n      for (const [genName, genMember] of genInfo.members) {\n        if (matchedExistMembers.has(genName)) continue; // name-matched in pass 1 (as an exist member) — skip\n        if (!genMember.docstring || !genMember.urlFingerprint) continue;\n        // Skip if this generated member was already name-matched\n        if (existInfo.members.has(genName)) continue;\n        const bucket = unmatchedGenByFp.get(genMember.urlFingerprint) ?? [];\n        bucket.push({ name: genName, member: genMember });\n        unmatchedGenByFp.set(genMember.urlFingerprint, bucket);\n      }\n      const unmatchedExistByFp = new Map<\n        string,\n        { name: string; member: typeof existInfo.members extends Map<string, infer V> ? V : never }[]\n      >();\n      for (const [existName, existMember] of existInfo.members) {\n        if (matchedExistMembers.has(existName)) continue;\n        if (!existMember.urlFingerprint) continue;\n        const bucket = unmatchedExistByFp.get(existMember.urlFingerprint) ?? [];\n        bucket.push({ name: existName, member: existMember });\n        unmatchedExistByFp.set(existMember.urlFingerprint, bucket);\n      }\n      for (const [fp, genBucket] of unmatchedGenByFp) {\n        if (genBucket.length !== 1) continue; // ambiguous — skip\n        const existBucket = unmatchedExistByFp.get(fp);\n        if (!existBucket || existBucket.length !== 1) continue; // ambiguous — skip\n        const genMember = genBucket[0].member;\n        const existEntry = existBucket[0];\n        const existMember = existEntry.member;\n        if (!genMember.docstring) continue;\n\n        if (existMember.docstring) {\n          const isPreserved = existMember.docstring.text.includes('@oagen-ignore');\n          if (isPreserved) continue;\n          if (existMember.docstring.text !== genMember.docstring.text) {\n            const newText = preserveDeprecatedTags(existMember.docstring.text, genMember.docstring.text);\n            const range = resolveDocRange(\n              result,\n              existMember.docstring.text,\n              existMember.declStartIndex,\n              existMember.docstring.startIndex,\n              existMember.docstring.endIndex,\n            );\n            edits.push({\n              start: range.start,\n              end: range.end,\n              newText,\n            });\n            docstringUpdates++;\n          }\n        } else {\n          const lineStart = declarationLineStart(result, existMember.declStartIndex);\n          const indent = ' '.repeat(existMember.declColumn);\n          edits.push({\n            start: lineStart,\n            end: lineStart,\n            newText: indent + genMember.docstring.text + '\\n',\n          });\n          docstringUpdates++;\n        }\n        matchedExistMembers.add(existEntry.name);\n      }\n    }\n\n    if (edits.length > 0) {\n      edits.sort((a, b) => b.start - a.start);\n      for (const edit of edits) {\n        result = result.slice(0, edit.start) + edit.newText + result.slice(edit.end);\n      }\n    }\n  }\n\n  const importsActuallyAdded =\n    toAppend.length > 0 || deepAdded > 0\n      ? adapter.renderImports\n        ? adapter.renderImports(newImports).length\n        : newImports.length\n      : 0;\n  const topLevelAdded = importsActuallyAdded + toAppend.length;\n  const totalAdded = topLevelAdded + deepAdded;\n\n  if (totalAdded === 0 && docstringUpdates === 0 && deepPruned === 0) {\n    return { content: existingContent, added: 0, preserved, changed: false };\n  }\n\n  return {\n    content: result,\n    added: totalAdded,\n    preserved,\n    changed: true,\n  };\n}\n","/**\n * Deep merge two parsed JSON values.\n *\n * - Objects: recursively merge, preserving existing keys not in generated\n * - Arrays: generated replaces existing entirely (generated owns array contents)\n * - Primitives: generated wins\n */\nexport function deepMergeJson(existing: unknown, generated: unknown): unknown {\n  if (\n    typeof existing === 'object' &&\n    existing !== null &&\n    !Array.isArray(existing) &&\n    typeof generated === 'object' &&\n    generated !== null &&\n    !Array.isArray(generated)\n  ) {\n    const merged: Record<string, unknown> = { ...(existing as Record<string, unknown>) };\n    for (const [key, value] of Object.entries(generated as Record<string, unknown>)) {\n      if (key in merged) {\n        merged[key] = deepMergeJson(merged[key], value);\n      } else {\n        merged[key] = value;\n      }\n    }\n    return merged;\n  }\n\n  // Arrays and primitives: generated wins\n  return generated;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { GeneratedFile } from './types.js';\nimport { mergeIntoExisting, hasGrammar, extractClassEndLines, extractStatements } from './merger.js';\nimport { deepMergeJson } from './json-merge.js';\nimport { getMergeAdapter } from './merge-adapters/index.js';\n\nexport interface WriteOptions {\n  /** The emitter language (e.g., \"node\", \"ruby\"). Used to select the\n   *  tree-sitter grammar for AST-level merging. */\n  language?: string;\n  /** The auto-generated file header string. */\n  header?: string;\n}\n\nexport interface WriteResult {\n  written: string[];\n  merged: string[];\n  skipped: string[];\n  identical: string[];\n  ignored: string[];\n}\n\n/**\n * Write generated files to disk with AST-level merging.\n *\n * When a file already exists:\n * - skipIfExists → leave it alone entirely\n * - AST merge available → parse both, append only new symbols\n * - No grammar → skip (never clobber hand-written code)\n *\n * New files are always written in full.\n */\nexport async function writeFiles(\n  files: GeneratedFile[],\n  outputDir: string,\n  options?: WriteOptions,\n): Promise<WriteResult> {\n  const result: WriteResult = {\n    written: [],\n    merged: [],\n    skipped: [],\n    identical: [],\n    ignored: [],\n  };\n  const sorted = [...files].sort((a, b) => a.path.localeCompare(b.path));\n  const language = options?.language;\n  const header = options?.header ?? '';\n\n  for (const file of sorted) {\n    const fullPath = path.join(outputDir, file.path);\n\n    // Repair on-disk casing when an emitter renames a generated file in a\n    // case-only way (e.g. `AuthenticationMfaFailed.kt` → `AuthenticationMFAFailed.kt`\n    // after adding `MFA` to an acronym list). On case-insensitive filesystems\n    // (APFS, NTFS) `writeFile` would otherwise reuse the existing inode and\n    // preserve the stale casing — surfacing later as ktlint/eslint errors.\n    await renameMismatchedCasing(fullPath);\n\n    // Check if file already exists\n    let existingContent: string | null = null;\n    try {\n      existingContent = await fs.readFile(fullPath, 'utf-8');\n    } catch {\n      // File doesn't exist\n    }\n\n    // New file → write in full\n    if (existingContent === null) {\n      await fs.mkdir(path.dirname(fullPath), { recursive: true });\n      await fs.writeFile(fullPath, file.content, 'utf-8');\n      result.written.push(file.path);\n      continue;\n    }\n\n    // skipIfExists → hard skip, no merge (but ensure header is present).\n    // JSON files are skipped from header injection because a leading `//`\n    // comment makes the file invalid JSON.\n    if (file.skipIfExists) {\n      if (header && !existingContent.startsWith(header) && !file.path.endsWith('.json')) {\n        await fs.writeFile(fullPath, header + '\\n\\n' + existingContent, 'utf-8');\n      }\n      result.skipped.push(file.path);\n      continue;\n    }\n\n    // @oagen-ignore-file → skip entirely (existing file opts out of all generation)\n    if (existingContent.includes('@oagen-ignore-file')) {\n      result.ignored.push(file.path);\n      continue;\n    }\n\n    // Don't merge test files into hand-written test files — generated tests are\n    // designed for the standalone generated SDK and will have wrong\n    // signatures/fixtures when merged into hand-written tests.\n    // However, if the existing test file is itself auto-generated (has the oagen\n    // header), allow overwriteExisting to take effect so new methods get coverage.\n    const adapter = language ? getMergeAdapter(language) : undefined;\n    const isTestFile = adapter?.testFilePatterns\n      ? adapter.testFilePatterns.some((p) => p.test(file.path))\n      : isDefaultTestFile(file.path);\n    if (isTestFile) {\n      const isExistingAutoGenerated = header && existingContent.startsWith(header);\n      if (!isExistingAutoGenerated && !file.overwriteExisting) {\n        result.skipped.push(file.path);\n        continue;\n      }\n      // Auto-generated test file or overwriteExisting — fall through to overwriteExisting / identical checks\n    }\n\n    // Identical content → no-op\n    if (existingContent === file.content) {\n      result.identical.push(file.path);\n      continue;\n    }\n\n    // Force overwrite — but preserve any @oagen-ignore regions from existing content\n    if (file.overwriteExisting) {\n      const content =\n        existingContent.includes('@oagen-ignore-start') && language && hasGrammar(language)\n          ? await overwriteWithPreservedRegions(existingContent, file.content, language)\n          : file.content;\n      await fs.writeFile(fullPath, content, 'utf-8');\n      result.written.push(file.path);\n      continue;\n    }\n\n    // JSON files → deep merge preserving existing keys\n    if (file.path.endsWith('.json')) {\n      try {\n        const existingJson = JSON.parse(existingContent);\n        const generatedJson = JSON.parse(file.content);\n        const merged = deepMergeJson(existingJson, generatedJson);\n        const mergedContent = JSON.stringify(merged, null, 2) + '\\n';\n        if (mergedContent === existingContent) {\n          result.identical.push(file.path);\n        } else {\n          await fs.writeFile(fullPath, mergedContent, 'utf-8');\n          result.merged.push(file.path);\n        }\n      } catch {\n        // Parse failed — fall back to overwrite\n        await fs.writeFile(fullPath, file.content, 'utf-8');\n        result.written.push(file.path);\n      }\n      continue;\n    }\n\n    // Source files with grammar → AST-level merge\n    if (language && hasGrammar(language)) {\n      try {\n        const mergeResult = await mergeIntoExisting(existingContent, file.content, language, header);\n\n        // Ensure header is present on merged content\n        let finalContent = mergeResult.content;\n        if (header && !finalContent.startsWith(header)) {\n          finalContent = header + '\\n\\n' + finalContent;\n        }\n\n        if (!mergeResult.changed && finalContent === existingContent) {\n          result.identical.push(file.path);\n          continue;\n        }\n\n        await fs.writeFile(fullPath, finalContent, 'utf-8');\n        result.merged.push(file.path);\n        continue;\n      } catch (err) {\n        // AST merge failed (e.g. tree-sitter grammar ABI issue) — fall back to overwrite\n        console.warn(\n          `[oagen] AST merge failed for ${file.path}, falling back to overwrite.${err instanceof Error ? ` ${err.message}` : ''}`,\n        );\n        await fs.writeFile(fullPath, file.content, 'utf-8');\n        result.written.push(file.path);\n        continue;\n      }\n    }\n\n    // No grammar available → skip to avoid clobbering\n    result.skipped.push(file.path);\n  }\n\n  return result;\n}\n\n/**\n * If a sibling exists with the same name except for letter case, rename it to\n * the requested casing. Uses a two-step rename via a temporary unique name so\n * case-insensitive filesystems (APFS on macOS, NTFS on Windows) actually\n * update the entry — `rename('Foo', 'FOO')` is a no-op on those systems.\n */\nasync function renameMismatchedCasing(fullPath: string): Promise<void> {\n  const dir = path.dirname(fullPath);\n  const target = path.basename(fullPath);\n  let entries: string[];\n  try {\n    entries = await fs.readdir(dir);\n  } catch {\n    return;\n  }\n  if (entries.includes(target)) return;\n  const targetLower = target.toLowerCase();\n  const mismatch = entries.find((e) => e.toLowerCase() === targetLower);\n  if (!mismatch) return;\n  const oldPath = path.join(dir, mismatch);\n  const tempPath = path.join(dir, `.oagen-case-${process.pid}-${Date.now()}-${target}`);\n  await fs.rename(oldPath, tempPath);\n  await fs.rename(tempPath, fullPath);\n}\n\n/** Comprehensive fallback when no adapter is available. */\nfunction isDefaultTestFile(filePath: string): boolean {\n  return (\n    /\\.(spec|test)\\.[jt]sx?$/.test(filePath) ||\n    filePath.endsWith('_test.go') ||\n    filePath.endsWith('_test.rb') ||\n    filePath.endsWith('_spec.rb') ||\n    /(?:^|\\/)test_.*\\.py$/.test(filePath) ||\n    filePath.endsWith('_test.py') ||\n    filePath.endsWith('Test.php') ||\n    filePath.endsWith('_test.rs') ||\n    /(?:^|\\/)tests\\/.*\\.rs$/.test(filePath)\n  );\n}\n\n// --- @oagen-ignore region preservation for overwriteExisting ---\n\n/**\n * Overwrite a file with generated content while preserving\n * `@oagen-ignore-start` / `@oagen-ignore-end` regions (and their\n * required imports) from the existing file.\n *\n * Uses tree-sitter via `extractClassEndLines` to find accurate class\n * boundaries so ignore blocks are inserted at the correct position even\n * when docstrings contain unindented text.\n */\nexport async function overwriteWithPreservedRegions(\n  existingContent: string,\n  generatedContent: string,\n  language: string,\n): Promise<string> {\n  const existingLines = existingContent.split('\\n');\n  const generatedLines = generatedContent.split('\\n');\n\n  // 1. Extract ignore blocks, their containing class, and the anchor line\n  //    (first non-blank line after the block in the existing file).\n  const blocks: { containingClass: string; containingScope: string; lines: string[]; anchor: string }[] = [];\n  for (let i = 0; i < existingLines.length; i++) {\n    if (!existingLines[i].includes('@oagen-ignore-start')) continue;\n    const startIdx = i;\n    while (i < existingLines.length && !existingLines[i].includes('@oagen-ignore-end')) i++;\n    let anchor = '';\n    for (let a = i + 1; a < existingLines.length; a++) {\n      if (existingLines[a].trim()) {\n        anchor = existingLines[a].trimStart();\n        break;\n      }\n    }\n    blocks.push({\n      containingClass: findContainingClass(existingLines, startIdx),\n      containingScope: findContainingDescribeScope(existingLines, startIdx),\n      lines: existingLines.slice(startIdx, i + 1),\n      anchor,\n    });\n  }\n  if (blocks.length === 0) return generatedContent;\n\n  // 2. Splice extra imports from existing into generated.\n  // First strip any `@oagen-ignore-start`..`@oagen-ignore-end` regions the\n  // generator itself emitted: we are about to re-insert the on-disk versions,\n  // and if we left the generator's seed blocks in place we'd end up with two\n  // copies of every ignore block per regeneration (monotonically growing).\n  const result = stripIgnoreRegions(generatedLines);\n  spliceExtraImports(existingLines, result);\n\n  // 3. Build class-end map from the generated content (after import splicing)\n  //    via tree-sitter for accurate boundary detection.\n  const genSource = result.join('\\n');\n  const classEndLines = await extractClassEndLines(genSource, language);\n\n  // 4. Group ignore blocks by class and determine insertion points\n  const blocksByClass = new Map<string, Array<{ containingScope: string; lines: string[]; anchor: string }>>();\n  for (const b of blocks) {\n    if (!blocksByClass.has(b.containingClass)) blocksByClass.set(b.containingClass, []);\n    blocksByClass.get(b.containingClass)!.push({\n      containingScope: b.containingScope,\n      lines: b.lines,\n      anchor: b.anchor,\n    });\n  }\n\n  // 4a. Handle replacement blocks: ignore blocks that redefine their\n  //     containing class replace the generated class entirely.\n  //     Also handles top-level blocks (no containing class) that define\n  //     a class matching one in the generated content.\n  const replacedClasses = new Set<string>();\n  const handledBlockKeys = new Set<string>();\n  const replacements: {\n    startLine: number;\n    endLine: number;\n    content: string[];\n  }[] = [];\n  for (const [className, classBlocks] of blocksByClass) {\n    // Determine the target class for replacement.  When the block has a\n    // containing class, we check if the block redefines that class.  When\n    // there is no containing class (top-level ignore block), we look for a\n    // class definition inside the block that matches a generated class.\n    let targetClass = className;\n    if (!targetClass) {\n      for (const entry of classBlocks) {\n        for (const l of entry.lines) {\n          const m = l.match(/^(?:export\\s+)?class\\s+(\\w+)/);\n          if (m && classEndLines.has(m[1])) {\n            targetClass = m[1];\n            break;\n          }\n        }\n        if (targetClass) break;\n      }\n    }\n    if (!targetClass) continue;\n    const isReplacement = classBlocks.some((entry) =>\n      entry.lines.some((l) => {\n        const m = l.match(/^(?:export\\s+)?class\\s+(\\w+)/);\n        return m?.[1] === targetClass;\n      }),\n    );\n    if (!isReplacement) continue;\n    const info = classEndLines.get(targetClass);\n    if (!info) continue;\n    const startLine = findClassDeclarationStart(result, targetClass, info.bodyEndLine);\n    if (startLine < 0) continue;\n    const content: string[] = [];\n    for (const entry of classBlocks) {\n      content.push('');\n      content.push(...entry.lines);\n    }\n    replacements.push({ startLine, endLine: info.bodyEndLine, content });\n    replacedClasses.add(targetClass);\n    handledBlockKeys.add(className);\n  }\n  // Apply replacements bottom-up to preserve line indices\n  replacements.sort((a, b) => b.startLine - a.startLine);\n  for (const rep of replacements) {\n    result.splice(rep.startLine, rep.endLine - rep.startLine, ...rep.content);\n  }\n\n  // 4a-bis. Top-level declarations protected by ignore regions win over their\n  //         generated counterparts. For each top-level block, drop generated\n  //         declarations (interface/type/const/function/…) whose names are\n  //         declared inside the block; the block content replaces the first\n  //         such declaration in place. Without this, every regeneration\n  //         re-emits a duplicate of each region-protected declaration.\n  let regionDeclarationEdits = 0;\n  {\n    const topLevelEntries = blocksByClass.get('');\n    if (topLevelEntries) {\n      // When 4a already placed the top-level blocks (as part of a class\n      // replacement), only delete generated duplicates — never re-insert.\n      const alreadyPlaced = handledBlockKeys.has('');\n      const remaining: typeof topLevelEntries = [];\n      for (const entry of topLevelEntries) {\n        const outcome = await applyRegionDeclarationOverride(result, entry.lines, language, !alreadyPlaced);\n        if (outcome.edited) regionDeclarationEdits++;\n        if (!alreadyPlaced && !outcome.placed) remaining.push(entry);\n      }\n      if (!alreadyPlaced) {\n        if (remaining.length === 0) {\n          blocksByClass.delete('');\n        } else {\n          blocksByClass.set('', remaining);\n        }\n      }\n    }\n  }\n\n  // 4b. Standard insertions for non-replacement blocks\n  // Rebuild class end lines if replacements shifted line numbers.\n  let effectiveClassEndLines = classEndLines;\n  if (replacedClasses.size > 0 || regionDeclarationEdits > 0) {\n    effectiveClassEndLines = await extractClassEndLines(result.join('\\n'), language);\n  }\n\n  const insertions: { line: number; order: number; content: string[] }[] = [];\n  let insertionOrder = 0;\n  for (const [className, classBlocks] of blocksByClass) {\n    if (handledBlockKeys.has(className) || replacedClasses.has(className)) continue;\n    const info = className ? effectiveClassEndLines.get(className) : undefined;\n\n    // Insert each block individually so each can use its own anchor.\n    for (const entry of classBlocks) {\n      let insertLine: number | undefined;\n\n      // Try anchor-based positioning: find the first line in the generated\n      // file whose trimmed-start content matches the anchor (the first\n      // non-blank line that followed this block in the existing file).\n      // Skip anchors that are just punctuation (braces, etc.) since they\n      // match too many locations. Accept doc comment starters (/** /// #)\n      // as valid anchors since they're structurally meaningful.\n      // Also skip bare language keywords (`end`, `end;`, `end)`) that appear\n      // on many lines and would match the wrong location (e.g. nesting the\n      // block inside a Ruby method body instead of at class level).\n      const isAmbiguousAnchor = /^end[;)\\s]*$/.test(entry.anchor);\n      if (\n        entry.anchor &&\n        !entry.anchor.includes('@oagen-ignore') &&\n        !isAmbiguousAnchor &&\n        /[a-zA-Z]|^\\/\\*|^\\/\\//.test(entry.anchor)\n      ) {\n        for (let li = 0; li < result.length; li++) {\n          if (result[li].trimStart() === entry.anchor) {\n            insertLine = li;\n            break;\n          }\n        }\n      }\n\n      // Fallback: class body end, or for top-level import blocks, after the\n      // last import line (so they stay near the top of the file, not at the\n      // bottom where they'd trigger E402 lint errors).\n      if (insertLine === undefined) {\n        if (info) {\n          insertLine = info.bodyEndLine;\n        } else {\n          const scopeEndLine = entry.containingScope\n            ? findDescribeScopeEndLine(result, entry.containingScope)\n            : undefined;\n          const blockHasImportsFallback = entry.lines.some((l: string) => /^\\s*(import|from)\\s/.test(l));\n          if (scopeEndLine !== undefined) {\n            insertLine = scopeEndLine;\n          } else if (blockHasImportsFallback || hasTopLevelDeclaration(entry.lines)) {\n            let lastImportLine = 0;\n            for (let li = 0; li < result.length; li++) {\n              const trimmed = result[li].trimStart();\n              if (/^(import|from)\\s/.test(trimmed)) lastImportLine = li + 1;\n            }\n            insertLine = lastImportLine;\n          } else {\n            insertLine = result.length;\n          }\n        }\n      }\n\n      // When inserting an import-containing ignore block, move up past\n      // blank separator lines so the block sits flush with surrounding\n      // imports (e.g., Kotlin's ktlint forbids blank lines within import\n      // blocks).\n      const blockHasImports = entry.lines.some((l: string) => /^\\s*import\\s/.test(l));\n      if (blockHasImports) {\n        while (\n          insertLine >= 2 &&\n          result[insertLine - 1]?.trim() === '' &&\n          /^\\s*(import|using|from)\\s/.test(result[insertLine - 2] ?? '')\n        ) {\n          insertLine--;\n        }\n      }\n\n      // Skip the leading blank line when the block is adjacent to imports\n      // or already preceded by a blank line (avoids double-blank-line gaps).\n      // Exclude C# `using` directives — StyleCop SA1515 requires a blank\n      // line before comments, so collapsing breaks the build.\n      const prevLine = insertLine > 0 ? (result[insertLine - 1]?.trimStart() ?? '') : '';\n      const prevIsImport = /^import\\s/.test(prevLine) || /^from\\s/.test(prevLine);\n      const prevIsBlank = insertLine > 0 && prevLine === '';\n      const blockContent = prevIsImport || prevIsBlank ? [...entry.lines] : ['', ...entry.lines];\n      // Add a trailing blank line when the next line is a doc comment\n      // (C# SA1514 requires a blank line before `///` doc headers).\n      const nextLine = result[insertLine]?.trimStart() ?? '';\n      if (nextLine.startsWith('///')) {\n        blockContent.push('');\n      }\n      insertions.push({ line: insertLine, order: insertionOrder++, content: blockContent });\n    }\n  }\n\n  // Apply bottom-up to preserve line indices. Blocks with the same insertion\n  // line must be applied in reverse discovery order because each splice inserts\n  // at the same index; otherwise repeated generation flips their order.\n  insertions.sort((a, b) => b.line - a.line || b.order - a.order);\n  for (const ins of insertions) {\n    result.splice(ins.line, 0, ...ins.content);\n  }\n\n  removeDuplicateImportsCoveredByIgnoreBlocks(result);\n\n  return result.join('\\n');\n}\n\n/**\n * Remove every `@oagen-ignore-start`..`@oagen-ignore-end` region from the\n * supplied lines, collapsing stretches of blank lines that get left behind.\n * Used to drop generator-emitted seed blocks before splicing the on-disk\n * versions back in — otherwise every regen doubles up.\n */\nfunction stripIgnoreRegions(lines: string[]): string[] {\n  const out: string[] = [];\n  let skipping = false;\n  for (const line of lines) {\n    if (!skipping && line.includes('@oagen-ignore-start')) {\n      skipping = true;\n      // Drop a preceding blank line if we have one queued up — otherwise\n      // regen leaves a stray blank line above the spliced-in block.\n      while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();\n      continue;\n    }\n    if (skipping) {\n      if (line.includes('@oagen-ignore-end')) skipping = false;\n      continue;\n    }\n    out.push(line);\n  }\n  return out;\n}\n\n/** Scan backwards from `lineIdx` to find the nearest class declaration name. */\nfunction findContainingClass(lines: string[], lineIdx: number): string {\n  if (/^\\S/.test(lines[lineIdx] ?? '')) return '';\n  // Allow leading whitespace and language-specific modifiers before `class`.\n  // Covers: `public class Foo` (C#/Java), `export class Foo` (TS),\n  // `class Foo` (Python/Ruby), `internal sealed class Foo` (C#), etc.\n  for (let j = lineIdx - 1; j >= 0; j--) {\n    const m = lines[j].match(\n      /^\\s*(?:(?:export|public|private|protected|internal|abstract|sealed|static|partial)\\s+)*class\\s+(\\w+)/,\n    );\n    if (m) return m[1];\n  }\n  return '';\n}\n\nfunction findContainingDescribeScope(lines: string[], lineIdx: number): string {\n  const markerLine = lines[lineIdx] ?? '';\n  if (/^\\S/.test(markerLine)) return '';\n  const markerIndent = leadingSpaces(markerLine);\n  for (let j = lineIdx - 1; j >= 0; j--) {\n    const line = lines[j];\n    const indent = leadingSpaces(line);\n    if (indent >= markerIndent) continue;\n    const match = line.match(/^\\s*describe\\((['\"`])(.+?)\\1\\s*,/);\n    if (match) return match[2];\n    if (/^\\s*(?:export\\s+)?class\\s+\\w+/.test(line)) return '';\n  }\n  return '';\n}\n\nfunction findDescribeScopeEndLine(lines: string[], scopeName: string): number | undefined {\n  for (let i = 0; i < lines.length; i++) {\n    const match = lines[i].match(/^\\s*describe\\((['\"`])(.+?)\\1\\s*,/);\n    if (!match || match[2] !== scopeName) continue;\n\n    let depth = 0;\n    for (let j = i; j < lines.length; j++) {\n      depth += countChar(lines[j], '{');\n      depth -= countChar(lines[j], '}');\n      if (j > i && depth <= 0) return j;\n    }\n  }\n  return undefined;\n}\n\nfunction leadingSpaces(line: string): number {\n  return line.match(/^\\s*/)?.[0].length ?? 0;\n}\n\nfunction countChar(line: string, char: string): number {\n  return [...line].filter((c) => c === char).length;\n}\n\nfunction hasTopLevelDeclaration(lines: string[]): boolean {\n  return lines.some((line) =>\n    /^(?:export\\s+)?(?:interface|type|class|function|const|let|var|enum)\\s+\\w+/.test(line.trim()),\n  );\n}\n\n/**\n * Find the start line of a class declaration (including decorators above it)\n * by scanning backwards from `beforeLine`.\n */\nfunction findClassDeclarationStart(lines: string[], className: string, beforeLine: number): number {\n  // Match optional indentation so Ruby/Python nested classes are found.\n  const classPattern = new RegExp(`^\\\\s*(?:export\\\\s+)?class\\\\s+${className}\\\\b`);\n  for (let i = beforeLine - 1; i >= 0; i--) {\n    if (!classPattern.test(lines[i])) continue;\n    // Scan backward past decorators\n    let start = i;\n    while (start > 0 && /^\\s*@\\w+/.test(lines[start - 1])) {\n      start--;\n    }\n    return start;\n  }\n  return -1;\n}\n\n// --- region-protected top-level declaration overrides ---\n\n/**\n * Conservative top-level declaration matcher for ignore-block content.\n * Matches column-0 declarations like `export interface X`, `type X = …`,\n * `const X = …`, `function X(…)`, `class X` (export optional). Names found\n * here are only acted on when the language's merge adapter also reports a\n * generated top-level statement with the same key, so false positives are\n * filtered by the real parser.\n */\nconst REGION_DECLARATION_PATTERN =\n  /^(?:export\\s+)?(?:declare\\s+)?(?:interface|type|enum|class|const|let|var|async\\s+function|function)\\s+([A-Za-z_$][\\w$]*)/;\n\n/** Extract top-level symbol names declared inside an ignore block's lines. */\nfunction collectRegionDeclaredNames(blockLines: string[]): Set<string> {\n  const names = new Set<string>();\n  for (const line of blockLines) {\n    if (line.includes('@oagen-ignore')) continue;\n    const m = line.match(REGION_DECLARATION_PATTERN);\n    if (m) names.add(m[1]);\n  }\n  return names;\n}\n\n/** Inclusive line ranges of `@oagen-ignore-start`..`@oagen-ignore-end` regions. */\nfunction collectIgnoreRegionLineRanges(lines: string[]): Array<{ start: number; end: number }> {\n  const ranges: Array<{ start: number; end: number }> = [];\n  let start = -1;\n  for (let i = 0; i < lines.length; i++) {\n    if (start === -1 && lines[i].includes('@oagen-ignore-start')) {\n      start = i;\n      continue;\n    }\n    if (start !== -1 && lines[i].includes('@oagen-ignore-end')) {\n      ranges.push({ start, end: i });\n      start = -1;\n    }\n  }\n  return ranges;\n}\n\n/**\n * Walk upward from a declaration's first line over its contiguous comment\n * block (doc comment), so the comment is dropped together with the\n * declaration. Stops at blank lines, region markers, and line 0 (a comment\n * on line 0 is the file header, not a docstring).\n */\nfunction extendOverPrecedingComments(lines: string[], startLine: number): number {\n  let s = startLine;\n  while (s > 1) {\n    const prev = lines[s - 1].trim();\n    if (prev === '' || prev.includes('@oagen-ignore')) break;\n    const isComment = prev.startsWith('//') || prev.startsWith('/*') || prev.startsWith('*') || prev.startsWith('#');\n    if (!isComment) break;\n    s--;\n  }\n  return s;\n}\n\n/**\n * Drop generated top-level declarations that are redeclared inside an ignore\n * block (\"region wins\"). When `placeBlock` is set and at least one generated\n * declaration matches, the block's lines replace the first match in place\n * (mirroring the class-replacement behavior above); any further matches are\n * deleted. Mutates `result` in place.\n *\n * Returns `placed` (the block content now lives in `result` and must not be\n * inserted again) and `edited` (line numbers shifted).\n */\nasync function applyRegionDeclarationOverride(\n  result: string[],\n  blockLines: string[],\n  language: string,\n  placeBlock: boolean,\n): Promise<{ placed: boolean; edited: boolean }> {\n  const names = collectRegionDeclaredNames(blockLines);\n  if (names.size === 0) return { placed: false, edited: false };\n\n  const source = result.join('\\n');\n  let parsed;\n  try {\n    parsed = await extractStatements(source, language);\n  } catch {\n    return { placed: false, edited: false };\n  }\n\n  const regionRanges = collectIgnoreRegionLineRanges(result);\n  const inRegion = (line: number) => regionRanges.some((r) => line >= r.start && line <= r.end);\n\n  const spans: Array<{ start: number; end: number }> = [];\n  for (const stmt of parsed.statements) {\n    if (stmt.kind !== 'declaration' || !stmt.key || !names.has(stmt.key)) continue;\n    // Locate the statement's line span; skip occurrences inside ignore\n    // regions (those ARE the protected content).\n    let idx = source.indexOf(stmt.text);\n    let startLine = -1;\n    while (idx !== -1) {\n      const line = source.slice(0, idx).split('\\n').length - 1;\n      if (!inRegion(line)) {\n        startLine = line;\n        break;\n      }\n      idx = source.indexOf(stmt.text, idx + 1);\n    }\n    if (startLine === -1) continue;\n    const endLine = startLine + stmt.text.split('\\n').length - 1;\n    spans.push({ start: extendOverPrecedingComments(result, startLine), end: endLine });\n  }\n  if (spans.length === 0) return { placed: false, edited: false };\n\n  spans.sort((a, b) => a.start - b.start);\n\n  // Delete all matches after the first, bottom-up to preserve indices.\n  for (let i = spans.length - 1; i >= 1; i--) {\n    const span = spans[i];\n    let deleteCount = span.end - span.start + 1;\n    // Collapse the blank separator the deletion leaves behind.\n    const prevBlank = span.start === 0 || (result[span.start - 1] ?? '').trim() === '';\n    const nextBlank = (result[span.end + 1] ?? '').trim() === '';\n    if (prevBlank && nextBlank && span.end + 1 < result.length) deleteCount++;\n    result.splice(span.start, deleteCount);\n  }\n\n  const first = spans[0];\n  if (placeBlock) {\n    result.splice(first.start, first.end - first.start + 1, ...blockLines);\n    return { placed: true, edited: true };\n  }\n\n  let deleteCount = first.end - first.start + 1;\n  const prevBlank = first.start === 0 || (result[first.start - 1] ?? '').trim() === '';\n  const nextBlank = (result[first.end + 1] ?? '').trim() === '';\n  if (prevBlank && nextBlank && first.end + 1 < result.length) deleteCount++;\n  result.splice(first.start, deleteCount);\n  return { placed: false, edited: true };\n}\n\n/**\n * Collect `from X import Y, Z` identifiers grouped by module, handling\n * both single-line and multiline (parenthesized) forms.\n */\nfunction collectFromImports(lines: string[]): Map<string, Set<string>> {\n  const byModule = new Map<string, Set<string>>();\n  for (let i = 0; i < lines.length; i++) {\n    if (!/^from\\s+/.test(lines[i])) continue;\n\n    let fullText = lines[i];\n    if (fullText.includes('(') && !fullText.includes(')')) {\n      while (i + 1 < lines.length) {\n        i++;\n        fullText += ' ' + lines[i].trim();\n        if (lines[i].includes(')')) break;\n      }\n    }\n\n    const normalized = fullText.replace(/[()]/g, '').replace(/\\s+/g, ' ').trim();\n    const match = normalized.match(/^from\\s+(\\S+)\\s+import\\s+(.+)$/);\n    if (!match) continue;\n\n    const mod = match[1];\n    if (!byModule.has(mod)) byModule.set(mod, new Set());\n    for (const id of match[2]\n      .split(',')\n      .map((s) => s.trim())\n      .filter(Boolean)) {\n      byModule.get(mod)!.add(id);\n    }\n  }\n  return byModule;\n}\n\n/**\n * Collected TypeScript imports grouped by form. Each map keys on the module\n * specifier (e.g. `./foo`, `node:fs`).\n */\ninterface TsImports {\n  /** `import { X, Y } from 'module'` — module → identifier names. */\n  named: Map<string, Set<string>>;\n  /** `import type { X } from 'module'` — module → identifier names. */\n  typeOnly: Map<string, Set<string>>;\n  /** `import X from 'module'` or `import type X from 'module'` — module → name. */\n  defaults: Map<string, string>;\n  /** `import * as X from 'module'` — module → namespace alias name. */\n  namespaces: Map<string, string>;\n  /** `import 'module'` — modules imported for side effects only. */\n  sideEffects: Set<string>;\n}\n\n/**\n * Collect TypeScript imports, grouped by form. Handles single-line and\n * multi-line `{ … }` named imports. Disjoint from Python's `from X import Y`\n * syntax so this can be called in parallel with `collectFromImports`.\n */\nfunction collectTsImports(lines: string[]): TsImports {\n  const out: TsImports = {\n    named: new Map(),\n    typeOnly: new Map(),\n    defaults: new Map(),\n    namespaces: new Map(),\n    sideEffects: new Set(),\n  };\n\n  for (let i = 0; i < lines.length; i++) {\n    const trimmed = lines[i].trim();\n    if (!/^import(\\s|$)/.test(trimmed)) continue;\n\n    // Accumulate multi-line `{ … }` imports.\n    let fullText = lines[i];\n    if (fullText.includes('{') && !fullText.includes('}')) {\n      while (i + 1 < lines.length) {\n        i++;\n        fullText += ' ' + lines[i].trim();\n        if (lines[i].includes('}')) break;\n      }\n    }\n\n    const normalized = fullText.replace(/\\s+/g, ' ').trim().replace(/;\\s*$/, '');\n\n    // `import 'module'`\n    let m = normalized.match(/^import\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      out.sideEffects.add(m[1]);\n      continue;\n    }\n\n    // `import * as X from 'module'`\n    m = normalized.match(/^import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      out.namespaces.set(m[2], m[1]);\n      continue;\n    }\n\n    // `import [Default,] { X, Y as Z } from 'module'` or `import type { X } from 'module'`\n    m = normalized.match(/^import\\s+(type\\s+)?(?:(\\w+)\\s*,\\s*)?\\{\\s*([^}]*)\\s*\\}\\s+from\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      const isTypeOnly = !!m[1];\n      const defaultName = m[2];\n      const namesRaw = m[3];\n      const mod = m[4];\n      if (defaultName) out.defaults.set(mod, defaultName);\n      const names = namesRaw\n        .split(',')\n        .map((s) => s.trim().replace(/\\s+as\\s+\\w+$/, ''))\n        .filter(Boolean);\n      for (const rawName of names) {\n        const isInlineTypeOnly = rawName.startsWith('type ');\n        const name = rawName.replace(/^type\\s+/, '');\n        const target = isTypeOnly || isInlineTypeOnly ? out.typeOnly : out.named;\n        if (!target.has(mod)) target.set(mod, new Set());\n        target.get(mod)!.add(name);\n      }\n      continue;\n    }\n\n    // `import X from 'module'` or `import type X from 'module'`\n    m = normalized.match(/^import\\s+(?:type\\s+)?(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]$/);\n    if (m) {\n      out.defaults.set(m[2], m[1]);\n      continue;\n    }\n  }\n\n  return out;\n}\n\n/**\n * Remove the given symbols from generated `import type` bindings, in place.\n *\n * Called when an existing *value* import for the same symbol is being spliced\n * back into the file. A value import satisfies both runtime and type uses, so\n * leaving the generated `import type { X }` would re-declare `X` (TS2300\n * duplicate identifier). Callers guarantee every symbol here is absent from\n * generated *value* imports, so each occurrence is type-only and safe to drop.\n *\n * Handles whole-line `import type { … }` and inline `import { …, type X }`,\n * single- or multi-line. A statement whose bindings all get stripped is\n * removed entirely.\n */\nfunction dropGeneratedTypeOnlyBindings(resultLines: string[], symbols: Set<string>): void {\n  if (symbols.size === 0) return;\n  const out: string[] = [];\n  for (let i = 0; i < resultLines.length; i++) {\n    const line = resultLines[i];\n    const trimmed = line.trim();\n    // Only named imports (with a brace) can carry the symbols we strip.\n    if (!/^import\\b/.test(trimmed) || !trimmed.includes('{')) {\n      out.push(line);\n      continue;\n    }\n    // Gather the full (possibly multi-line) `{ … }` statement.\n    const span = [line];\n    while (!span.join(' ').includes('}') && i + 1 < resultLines.length) {\n      i++;\n      span.push(resultLines[i]);\n    }\n    const normalized = span.join(' ').replace(/\\s+/g, ' ').trim().replace(/;\\s*$/, '');\n    const m = normalized.match(/^import\\s+(type\\s+)?(?:(\\w+)\\s*,\\s*)?\\{\\s*([^}]*)\\s*\\}\\s+from\\s+(['\"][^'\"]+['\"])$/);\n    if (!m) {\n      for (const s of span) out.push(s);\n      continue;\n    }\n    const isTypeOnly = !!m[1];\n    const defaultName = m[2];\n    const items = m[3]\n      .split(',')\n      .map((s) => s.trim())\n      .filter(Boolean);\n    const modQuoted = m[4];\n    const kept = items.filter((raw) => {\n      const isTypeBinding = isTypeOnly || raw.startsWith('type ');\n      const bare = raw.replace(/^type\\s+/, '');\n      return !(isTypeBinding && symbols.has(bare));\n    });\n    if (kept.length === items.length) {\n      // Nothing stripped — preserve the original lines verbatim.\n      for (const s of span) out.push(s);\n      continue;\n    }\n    if (kept.length === 0 && !defaultName) continue; // statement fully emptied\n    const lead = line.match(/^(\\s*)/)?.[1] ?? '';\n    const prefix = isTypeOnly ? 'import type ' : 'import ';\n    const defaultPart = defaultName ? `${defaultName}, ` : '';\n    out.push(`${lead}${prefix}${defaultPart}{ ${kept.join(', ')} } from ${modQuoted};`);\n  }\n  resultLines.splice(0, resultLines.length, ...out);\n}\n\n/**\n * Add imports from the existing file that are absent from the generated\n * result. Handles:\n *\n * - Python: `import X` and `from X import Y`\n * - TypeScript: `import { X } from 'module'`, `import type { X } from 'module'`,\n *   `import X from 'module'`, `import * as X from 'module'`, `import 'module'`\n * - PHP: `use Foo\\Bar;` and `use Foo\\Bar as Baz;` (namespace-qualified only)\n * - Ruby: `require '…'` and `require_relative '…'`\n *\n * Mutates `resultLines` in place.\n */\nfunction filterOutIgnoreRegions(lines: string[]): string[] {\n  const out: string[] = [];\n  let skipping = false;\n  for (const line of lines) {\n    if (!skipping && line.includes('@oagen-ignore-start')) {\n      skipping = true;\n      continue;\n    }\n    if (skipping) {\n      if (line.includes('@oagen-ignore-end')) skipping = false;\n      continue;\n    }\n    out.push(line);\n  }\n  return out;\n}\n\nfunction collectIgnoreRegionUsageText(lines: string[]): string {\n  const out: string[] = [];\n  let skipping = false;\n  for (const line of lines) {\n    if (!skipping && line.includes('@oagen-ignore-start')) {\n      skipping = true;\n      continue;\n    }\n    if (!skipping) continue;\n    if (/^\\s*(import|from)\\s/.test(line)) continue;\n    out.push(line);\n    if (line.includes('@oagen-ignore-end')) skipping = false;\n  }\n  return out.join('\\n');\n}\n\nfunction removeDuplicateImportsCoveredByIgnoreBlocks(lines: string[]): void {\n  const ignoredImports = new Set<string>();\n  const importStatements = collectImportStatements(lines);\n  for (const stmt of importStatements) {\n    if (stmt.inIgnore) ignoredImports.add(normalizeImportStatement(stmt.lines));\n  }\n  if (ignoredImports.size === 0) return;\n\n  for (const stmt of [...importStatements].reverse()) {\n    if (stmt.inIgnore) continue;\n    if (ignoredImports.has(normalizeImportStatement(stmt.lines))) {\n      lines.splice(stmt.start, stmt.end - stmt.start + 1);\n    }\n  }\n}\n\nfunction collectImportStatements(\n  lines: string[],\n): Array<{ start: number; end: number; lines: string[]; inIgnore: boolean }> {\n  const statements: Array<{ start: number; end: number; lines: string[]; inIgnore: boolean }> = [];\n  let inIgnore = false;\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i];\n    if (!inIgnore && line.includes('@oagen-ignore-start')) {\n      inIgnore = true;\n      continue;\n    }\n    if (inIgnore && line.includes('@oagen-ignore-end')) {\n      inIgnore = false;\n      continue;\n    }\n    if (!isImportLine(line)) continue;\n\n    const start = i;\n    let end = i;\n    const statementLines = [line];\n    const opens = (line.match(/[({]/g) ?? []).length;\n    const closes = (line.match(/[)}]/g) ?? []).length;\n    if (opens > closes) {\n      while (end + 1 < lines.length) {\n        end++;\n        statementLines.push(lines[end]);\n        if ((lines[end].match(/[)}]/g) ?? []).length > 0 && /\\bfrom\\b/.test(lines[end])) break;\n      }\n      i = end;\n    }\n    statements.push({ start, end, lines: statementLines, inIgnore });\n  }\n  return statements;\n}\n\nfunction normalizeImportStatement(lines: string[]): string {\n  return lines.join('\\n').replace(/,\\s*}/g, ' }').replace(/\\s+/g, ' ').trim();\n}\n\nfunction isImportLine(line: string): boolean {\n  const trimmed = line.trim();\n  return (\n    /^import(\\s|$)/.test(trimmed) ||\n    /^from\\s+/.test(trimmed) ||\n    /^use\\s+[\\w\\\\]/.test(trimmed) ||\n    /^require(_relative)?\\s+['\"]/.test(trimmed)\n  );\n}\n\nfunction identifierUsed(source: string, identifier: string): boolean {\n  return new RegExp(`\\\\b${identifier.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(source);\n}\n\nfunction spliceExtraImports(existingLines: string[], resultLines: string[]): void {\n  // Imports inside @oagen-ignore regions are converted into normal imports\n  // only when non-import ignore content still references them. This prevents\n  // stale import-only ignore blocks from creating duplicate or unused imports.\n  const existingOutsideIgnore = filterOutIgnoreRegions(existingLines);\n  const ignoreRegionText = collectIgnoreRegionUsageText(existingLines);\n\n  // Python-style `import hashlib`. Excludes TS forms like `import X from '…'`\n  // (have a `from` clause) and TS multi-line type imports whose first line is\n  // `import type {` (have a brace) — both are handled by the TS collector\n  // below.\n  const isPythonSimpleImport = (l: string) => /^import\\s+\\w/.test(l) && !/\\sfrom\\s/.test(l) && !/[{}]/.test(l);\n\n  // Simple imports (import hashlib, import json, …)\n  const existingSimple = new Set(existingOutsideIgnore.filter(isPythonSimpleImport).map((l) => l.trim()));\n  const generatedSimple = new Set(resultLines.filter(isPythonSimpleImport).map((l) => l.trim()));\n  const extraSimple = [...existingSimple].filter((l) => !generatedSimple.has(l));\n\n  // From-imports — compare by module and find extra identifiers\n  const existingFrom = collectFromImports(existingOutsideIgnore);\n  const generatedFrom = collectFromImports(resultLines);\n\n  // Build a set of all identifiers imported by the generated file (across all modules)\n  // so we can detect when an existing barrel import's identifiers are covered by\n  // more-specific generated imports (e.g., `from x.y import Z` covers `from x import Z`).\n  const allGeneratedIds = new Set<string>();\n  for (const ids of generatedFrom.values()) {\n    for (const id of ids) allGeneratedIds.add(id);\n  }\n\n  const extraFromLines: string[] = [];\n  for (const [mod, existIds] of existingFrom) {\n    const genIds = generatedFrom.get(mod);\n    if (!genIds) {\n      // The exact module isn't in the generated file — but check whether every\n      // identifier is already imported from a different (e.g., more-specific) module.\n      const extra = [...existIds].filter((id) => !allGeneratedIds.has(id));\n      if (extra.length > 0) {\n        extraFromLines.push(`from ${mod} import ${extra.join(', ')}`);\n      }\n    } else {\n      const extra = [...existIds].filter((id) => !genIds.has(id) && !allGeneratedIds.has(id));\n      if (extra.length > 0) {\n        extraFromLines.push(`from ${mod} import ${extra.join(', ')}`);\n      }\n    }\n  }\n\n  // TypeScript imports.\n  const existingTs = collectTsImports(existingOutsideIgnore);\n  const generatedTs = collectTsImports(resultLines);\n  const extraTsLines: string[] = [];\n\n  // Bindings the generated file imports anywhere, split by capability.\n  //\n  // `allGeneratedTsIds` — every binding regardless of module. The generator\n  // frequently imports a symbol from a concrete file\n  // (`./interfaces/connection.interface`) while the existing hand-written file\n  // imported the same symbol from a barrel (`./interfaces`). Splicing the\n  // barrel form back in would re-declare the binding (TS2300 duplicate\n  // identifier), so a symbol already in scope satisfies a *type* use and is\n  // never re-imported as a type even from a different specifier.\n  //\n  // `generatedValueIds` — only runtime-capable bindings (named / default /\n  // namespace, never `import type`). A *value* use is satisfied only by one of\n  // these: an `import type` binding is erased at compile time and cannot back a\n  // runtime reference inside a preserved region. So a generated `import type`\n  // must NOT suppress an existing value import of the same symbol.\n  const allGeneratedTsIds = new Set<string>();\n  const generatedValueIds = new Set<string>();\n  for (const ids of generatedTs.named.values())\n    for (const id of ids) {\n      allGeneratedTsIds.add(id);\n      generatedValueIds.add(id);\n    }\n  for (const ids of generatedTs.typeOnly.values()) for (const id of ids) allGeneratedTsIds.add(id);\n  for (const name of generatedTs.defaults.values()) {\n    allGeneratedTsIds.add(name);\n    generatedValueIds.add(name);\n  }\n  for (const name of generatedTs.namespaces.values()) {\n    allGeneratedTsIds.add(name);\n    generatedValueIds.add(name);\n  }\n\n  // Symbols the generated file imports type-only that we are nonetheless\n  // re-splicing as value imports (because a preserved region needs the runtime\n  // binding). The spliced value import also covers the type use, so the\n  // generated `import type` for the symbol must be dropped or the two collide\n  // (TS2300). Collected during the loops below, applied just before splicing.\n  const reclaimedValueIds = new Set<string>();\n  const generatedHasValue = (id: string): boolean => generatedValueIds.has(id);\n  const generatedHasTypeOnly = (id: string): boolean => allGeneratedTsIds.has(id) && !generatedValueIds.has(id);\n\n  for (const mod of existingTs.sideEffects) {\n    if (!generatedTs.sideEffects.has(mod)) extraTsLines.push(`import '${mod}';`);\n  }\n  for (const [mod, name] of existingTs.defaults) {\n    if (generatedTs.defaults.has(mod)) continue;\n    if (!identifierUsed(ignoreRegionText, name)) continue;\n    if (generatedHasValue(name)) continue;\n    if (generatedHasTypeOnly(name)) reclaimedValueIds.add(name);\n    extraTsLines.push(`import ${name} from '${mod}';`);\n  }\n  for (const [mod, name] of existingTs.namespaces) {\n    if (!identifierUsed(ignoreRegionText, name)) continue;\n    if (generatedHasValue(name)) continue;\n    if (generatedTs.namespaces.has(mod)) continue;\n    if (generatedHasTypeOnly(name)) reclaimedValueIds.add(name);\n    extraTsLines.push(`import * as ${name} from '${mod}';`);\n  }\n  for (const [mod, existIds] of existingTs.named) {\n    const extra = [...existIds].filter((id) => !generatedHasValue(id) && identifierUsed(ignoreRegionText, id));\n    for (const id of extra) if (generatedHasTypeOnly(id)) reclaimedValueIds.add(id);\n    if (extra.length > 0) extraTsLines.push(`import { ${extra.join(', ')} } from '${mod}';`);\n  }\n  for (const [mod, existIds] of existingTs.typeOnly) {\n    const extra = [...existIds].filter((id) => !allGeneratedTsIds.has(id) && identifierUsed(ignoreRegionText, id));\n    if (extra.length > 0) extraTsLines.push(`import type { ${extra.join(', ')} } from '${mod}';`);\n  }\n\n  // Drop reclaimed symbols from generated `import type` lines so the value\n  // imports spliced above do not duplicate them.\n  dropGeneratedTypeOnlyBindings(resultLines, reclaimedValueIds);\n\n  // PHP `use Foo\\Bar;` and `use Foo\\Bar as Baz;` — namespace-qualified only\n  // (a backslash anywhere in the path) so this doesn't mistakenly hoist\n  // single-segment in-class trait references like `use TraitName;`.\n  const isPhpUseImport = (l: string) => /^use\\s+[\\w\\\\]+\\\\[\\w\\\\]*(\\s+as\\s+\\w+)?\\s*;?$/.test(l);\n  const existingPhpUse = new Set(existingOutsideIgnore.filter(isPhpUseImport).map((l) => l.trim()));\n  const generatedPhpUse = new Set(resultLines.filter(isPhpUseImport).map((l) => l.trim()));\n  const extraPhpUse = [...existingPhpUse].filter((l) => !generatedPhpUse.has(l));\n\n  // Ruby `require '...'` and `require_relative '...'`. Dedupe by (kind, path)\n  // so quote style differs without producing duplicates — e.g. when the\n  // emitter writes `require 'json'` but a Ruby formatter has rewritten the\n  // on-disk copy to `require \"json\"`.\n  const rubyRequireRe = /^(require(?:_relative)?)\\s+['\"]([^'\"]+)['\"]\\s*$/;\n  const rubyRequireKey = (l: string): string | undefined => {\n    const m = l.trim().match(rubyRequireRe);\n    return m ? `${m[1]}\\t${m[2]}` : undefined;\n  };\n  const generatedRubyRequireKeys = new Set<string>();\n  for (const l of resultLines) {\n    const key = rubyRequireKey(l);\n    if (key) generatedRubyRequireKeys.add(key);\n  }\n  const seenExistingKeys = new Set<string>();\n  const extraRubyRequire: string[] = [];\n  for (const l of existingOutsideIgnore) {\n    const key = rubyRequireKey(l);\n    if (!key) continue;\n    if (generatedRubyRequireKeys.has(key)) continue;\n    if (seenExistingKeys.has(key)) continue;\n    seenExistingKeys.add(key);\n    extraRubyRequire.push(l.trim());\n  }\n\n  const allExtra = [...extraSimple, ...extraFromLines, ...extraTsLines, ...extraPhpUse, ...extraRubyRequire];\n  if (allExtra.length === 0) return;\n\n  // Find last import line in resultLines (accounting for multiline imports).\n  // Recognizes Python (`from X import Y`, `import X`), TS (`import …`), PHP\n  // (`use …`), and Ruby (`require`, `require_relative`).\n  const isImportStart = (l: string) =>\n    /^\\s*import(\\s|$)/.test(l) ||\n    /^from\\s+/.test(l) ||\n    /^\\s*use\\s+[\\w\\\\]/.test(l) ||\n    /^\\s*require(_relative)?\\s+['\"]/.test(l);\n  let lastImportIdx = -1;\n  for (let i = 0; i < resultLines.length; i++) {\n    if (!isImportStart(resultLines[i])) continue;\n    lastImportIdx = i;\n    const opens = (resultLines[i].match(/[({]/g) ?? []).length;\n    const closes = (resultLines[i].match(/[)}]/g) ?? []).length;\n    if (opens > closes) {\n      while (i + 1 < resultLines.length) {\n        i++;\n        lastImportIdx = i;\n        if ((resultLines[i].match(/[)}]/g) ?? []).length > 0) break;\n      }\n    }\n  }\n\n  if (lastImportIdx >= 0) {\n    resultLines.splice(lastImportIdx + 1, 0, ...allExtra);\n    return;\n  }\n\n  // No import survived in the generated file (e.g. its only import was a\n  // type-only line reclaimed above). Insert after any leading comment header\n  // so the spliced imports still land at the top of the file.\n  let insertAt = 0;\n  let inBlockComment = false;\n  for (let i = 0; i < resultLines.length; i++) {\n    const t = resultLines[i].trim();\n    if (inBlockComment) {\n      insertAt = i + 1;\n      if (t.includes('*/')) inBlockComment = false;\n      continue;\n    }\n    if (t.startsWith('//')) {\n      insertAt = i + 1;\n      continue;\n    }\n    if (t.startsWith('/*')) {\n      insertAt = i + 1;\n      inBlockComment = !t.includes('*/');\n      continue;\n    }\n    break; // first blank or code line — stop here\n  }\n  resultLines.splice(insertAt, 0, ...allExtra);\n}\n","import { resolveMountTarget } from '../ir/operation-hints.js';\nimport type { ApiSpec } from '../ir/types.js';\n\n/**\n * Validate a `--services` selection and return it as a set of POST-MOUNT service\n * names for emitters to scope on.\n *\n * Scoped generation does NOT filter the IR: model placement, dedup/aliasing, and\n * shared-schema decisions are global computations over the full service/model set\n * (filtering them churns shared `common/` files). Instead the full spec flows to\n * the emitters unchanged and this set is passed as `ctx.scopedServices`; each\n * emitter gates only its per-service resource/test emission on it.\n *\n * Matching is on the POST-MOUNT name. Mount resolution never mutates\n * `spec.services` — the post-mount target lives on `ResolvedOperation.mountOn`\n * (`mountOn = hint?.mountOn ?? resolveMountTarget(service.name, mountRules)`) — so\n * the post-mount name of a source service is derived here with the same\n * `resolveMountTarget` (exact rules and trailing-`*` prefix rules, longest\n * prefix wins). Selecting a target (e.g.\n * `DirectorySync`) is valid because every source tag that mounts into it\n * (`DirectoryUsers`, `DirectoryGroups`, …) shares that post-mount name, and the\n * emitters group resources by mount, so all siblings emit together.\n *\n * @param spec - The parsed API spec (never mutated; never filtered).\n * @param selected - Post-mount service names from `--services` (normalized/trimmed).\n * @param mountRules - Source-service-name (exact or trailing-`*` prefix pattern)\n *   → post-mount-target mappings.\n * @returns The validated selection as a `Set` of post-mount names.\n * @throws A `ConfigError` listing valid post-mount names when a selection is\n *   unknown — scoped generation never silently emits the wrong set.\n */\n/**\n * Canonicalize a service name to a casing/separator-insensitive key so that\n * `MultiFactorAuth` (post-mount IR name), `multi_factor_auth` (snake-cased\n * manifest record), and `multiFactorAuth` (camel-cased manifest record) all\n * collapse to `multifactorauth`. Used to match a spec service against the\n * services a prior manifest recorded as already on disk, where the casing of\n * the recorded `service` field varies per emitter.\n */\nexport function canonicalServiceKey(name: string): string {\n  return name.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n\nexport function resolveScopedServices(\n  spec: ApiSpec,\n  selected: string[],\n  mountRules?: Record<string, string>,\n): Set<string> {\n  const mounts = mountRules ?? {};\n  const validPostMount = new Set(spec.services.map((s) => resolveMountTarget(s.name, mounts)));\n  const selectedSet = new Set(selected);\n\n  const unknown = [...selectedSet].filter((s) => !validPostMount.has(s));\n  if (unknown.length > 0) {\n    const err = new Error(\n      `Unknown --services: ${unknown.sort().join(', ')}. ` +\n        `Valid post-mount services: ${[...validPostMount].sort().join(', ')}`,\n    );\n    err.name = 'ConfigError';\n    throw err;\n  }\n\n  return selectedSet;\n}\n","import type { ApiSpec, Model, TypeRef, Service, Operation, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  collectResponseHeaders,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectWebhookTypeRefs,\n} from '../ir/types.js';\nimport type { OperationHint } from '../ir/operation-hints.js';\nimport { resolveOperations } from '../ir/operation-hints.js';\nimport type { Emitter, EmitterContext, GeneratedFile, OperationsMap } from './types.js';\nimport type { ApiSurface, OverlayLookup } from '../compat/types.js';\nimport { toSnakeCase } from '../utils/naming.js';\nimport { canonicalServiceKey } from './scoped-services.js';\n\nexport function buildEmitterContext(\n  spec: ApiSpec,\n  options: {\n    namespace: string;\n    outputDir: string;\n    apiSurface?: ApiSurface;\n    overlayLookup?: OverlayLookup;\n    operationHints?: Record<string, OperationHint>;\n    mountRules?: Record<string, string>;\n    modelHints?: Record<string, string>;\n    emitterOptions?: Record<string, unknown>;\n    target?: string;\n    priorTargetManifestPaths?: Set<string>;\n    scopedServices?: Set<string>;\n    presentServiceKeys?: Set<string>;\n  },\n): EmitterContext {\n  const resolvedOperations = resolveOperations(spec, options.operationHints, options.mountRules);\n\n  // In a scoped run, derive the model/enum allow-lists = names reachable from the\n  // SELECTED source services only (those whose post-mount target is selected).\n  // Emitters write a model/enum FILE only when it is in these sets, so a\n  // non-selected service's models/enums are left byte-for-byte untouched — even\n  // when their spec drifted. Barrels/clients still reference every on-disk\n  // service (aggregateSurfaceServices), so those untouched files stay importable.\n  //\n  // This is the MINIMAL-scope contract: a scoped `--services X` run touches only\n  // X's own files. It relies on the emitters correspondingly NOT regenerating\n  // present services' fixtures and skipping the wholesale round-trip test in a\n  // scoped run — otherwise a fresh fixture would assert a field the (untouched)\n  // present model lacks. The three must move together; keeping the whole surface\n  // consistent instead (the prior behaviour) is the trade-off we chose against:\n  // it made every scoped run flush all on-disk drift, defeating the point of\n  // scoping. The SDK may lag on non-selected services until they're regenerated.\n  let scopedModelNames: Set<string> | undefined;\n  let scopedEnumNames: Set<string> | undefined;\n  if (options.scopedServices && options.scopedServices.size > 0) {\n    const selected = options.scopedServices;\n    // Seed reachability from ONLY the operations that mount to a selected target\n    // — not from every operation of a source service that has one op mounted\n    // there. `resolveOperations` honours per-operation `mountOn` hints, so a\n    // single source service can split across targets; collecting the whole\n    // service would pull its sibling operations' models (mounted elsewhere) into\n    // scope and regenerate non-selected model files, breaking the selected-only\n    // contract. Build temp services carrying just the selected operations.\n    const selectedOpsByService = new Map<string, Operation[]>();\n    for (const r of resolvedOperations) {\n      if (!selected.has(r.mountOn)) continue;\n      const ops = selectedOpsByService.get(r.service.name) ?? [];\n      ops.push(r.operation);\n      selectedOpsByService.set(r.service.name, ops);\n    }\n    const selectedSourceServices = spec.services\n      .filter((s) => selectedOpsByService.has(s.name))\n      .map((s) => ({ ...s, operations: selectedOpsByService.get(s.name)! }));\n    const reachable = collectReferencedNames(selectedSourceServices, spec.models, { preserveAllDiscriminated: false });\n    scopedModelNames = reachable.models;\n    scopedEnumNames = reachable.enums;\n  }\n\n  return {\n    namespace: toSnakeCase(options.namespace),\n    namespacePascal: options.namespace,\n    spec,\n    outputDir: options.outputDir,\n    apiSurface: options.apiSurface,\n    overlayLookup: options.overlayLookup,\n    resolvedOperations,\n    modelHints: options.modelHints,\n    emitterOptions: options.emitterOptions,\n    targetDir: options.target,\n    priorTargetManifestPaths: options.priorTargetManifestPaths,\n    scopedServices: options.scopedServices,\n    presentServiceKeys: options.presentServiceKeys,\n    scopedModelNames,\n    scopedEnumNames,\n  };\n}\n\n/**\n * The services an aggregate (barrel/client/test) generator may reference in a\n * scoped run: the selected services plus every service the prior manifest\n * recorded as already on disk. A service the spec just added that is neither\n * selected nor already generated is excluded — otherwise the client/barrels\n * would import a resource/model whose file this run does not emit (the orphaned\n * `agents/__init__.py → ._resource` class of build break).\n *\n * Outside a scoped run (full generation), every service is in surface.\n */\nexport function aggregateSurfaceServices(spec: ApiSpec, ctx: EmitterContext): Service[] {\n  const scope = ctx.scopedServices;\n  if (!scope || scope.size === 0) return spec.services;\n  const present = ctx.presentServiceKeys ?? new Set<string>();\n  const postMountOf = (service: Service): string =>\n    ctx.resolvedOperations?.find((r) => r.service.name === service.name)?.mountOn ?? service.name;\n  return spec.services.filter((s) => {\n    const postMount = postMountOf(s);\n    return scope.has(postMount) || present.has(canonicalServiceKey(postMount));\n  });\n}\n\n/**\n * Collect model and enum names transitively referenced by service operations.\n * Walks operation parameters, request bodies, responses, and pagination item\n * and envelope types, then chases model field references until the set stabilizes.\n */\nexport function collectReferencedNames(\n  services: Service[],\n  models: Model[],\n  opts: { preserveAllDiscriminated?: boolean; webhooks?: Webhook[] } = {},\n): { models: Set<string>; enums: Set<string> } {\n  // Default: preserve EVERY discriminated/event model as public surface (full\n  // emission). Strict mode (`preserveAllDiscriminated: false`, used to compute a\n  // scoped run's reachable set) skips that blanket and instead chases the mapping\n  // variants of discriminated models that are actually reached — so a scoped\n  // service doesn't pull in the entire unrelated event tree.\n  const preserveAllDiscriminated = opts.preserveAllDiscriminated !== false;\n  const referencedModels = new Set<string>();\n  const referencedEnums = new Set<string>();\n\n  const collectFromTypeRef = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      model: (r) => referencedModels.add(r.name),\n      enum: (r) => referencedEnums.add(r.name),\n    });\n  };\n\n  // Seed: walk every operation's params, request body, response, errors, and pagination\n  for (const service of services) {\n    for (const op of service.operations) {\n      for (const p of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        collectFromTypeRef(p.type);\n      }\n      if (op.requestBody) collectFromTypeRef(op.requestBody);\n      for (const { type } of collectRequestBodyTypes(op)) collectFromTypeRef(type);\n      collectFromTypeRef(op.response);\n      if (op.pagination) {\n        collectFromTypeRef(op.pagination.itemType);\n        for (const field of op.pagination.envelopeFields ?? []) collectFromTypeRef(field.type);\n      }\n      for (const header of collectResponseHeaders(op)) collectFromTypeRef(header.type);\n      for (const { type } of collectResponseBodyTypes(op)) collectFromTypeRef(type);\n      for (const err of op.errors) {\n        if (err.type) collectFromTypeRef(err.type);\n      }\n      if (op.successResponses) {\n        for (const sr of op.successResponses) {\n          collectFromTypeRef(sr.type);\n        }\n      }\n    }\n  }\n\n  // A webhook payload or header type is public surface an emitter hands the\n  // user, so it seeds reachability like an operation's types; without this a\n  // model referenced only by a webhook would be pruned as an orphan.\n  for (const webhook of opts.webhooks ?? []) {\n    for (const ref of collectWebhookTypeRefs(webhook)) collectFromTypeRef(ref);\n  }\n\n  // Preserve discriminated models as public SDK types even when no operation\n  // returns them directly. This matters for event/webhook unions where the base\n  // operation references a generic envelope but the variant structs are still\n  // useful public surface.\n  //\n  // Also preserve the variants mapped from an `allOf [base, oneOf […]]` base\n  // (carried as `Model.discriminator.mapping`). The base model is reached\n  // through the operation; without explicitly chasing its mapping, the\n  // variant structs would be unreachable and the dispatcher would dangle\n  // imports.\n  if (preserveAllDiscriminated) {\n    for (const model of models) {\n      if (isDiscriminatedModel(model)) {\n        referencedModels.add(model.name);\n      }\n      const disc = model.discriminator;\n      if (disc?.mapping) {\n        for (const variantName of Object.values(disc.mapping)) {\n          referencedModels.add(variantName);\n        }\n      }\n    }\n  }\n\n  // Chase: transitively resolve model field references until stable\n  const modelsByName = new Map(models.map((m) => [m.name, m]));\n  const visited = new Set<string>();\n  const queue = [...referencedModels];\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (visited.has(name)) continue;\n    visited.add(name);\n    const model = modelsByName.get(name);\n    if (!model) continue;\n    // A reached discriminated base pulls in its mapping variants (the dispatcher\n    // would otherwise dangle). In full mode this is redundant with the blanket\n    // pass above; in strict mode it is the only path that includes variants.\n    const disc = model.discriminator;\n    if (disc?.mapping) {\n      for (const variantName of Object.values(disc.mapping)) {\n        if (!referencedModels.has(variantName)) {\n          referencedModels.add(variantName);\n          queue.push(variantName);\n        }\n      }\n    }\n    // Fields and, for a named union, its variants: a union alias dangles\n    // without the models it is a union of.\n    for (const ref of collectModelTypeRefs(model)) {\n      collectFromTypeRef(ref);\n      // If new models were discovered, enqueue them\n      for (const m of referencedModels) {\n        if (!visited.has(m)) queue.push(m);\n      }\n    }\n  }\n\n  return { models: referencedModels, enums: referencedEnums };\n}\n\nfunction isDiscriminatedModel(model: Model): boolean {\n  return model.fields.some(\n    (field) =>\n      (field.name === 'event' || field.name === 'type' || field.name === 'object') && field.type.kind === 'literal',\n  );\n}\n\n/**\n * Collect all generated files from an emitter (no headers, no path prefixes).\n *\n * A full run emits over the whole spec. A scoped (`--services`) run still emits\n * model placement, dedup, the root client, and aggregate/barrel files\n * byte-identically for every service ALREADY on disk (plus the brand-new\n * selected service, which is wired into the client automatically) — but it\n * narrows that surface to `selected ∪ already-on-disk` services\n * (`aggregateSurfaceServices`). A service the spec just added that is neither\n * selected nor already generated is dropped from the surface entirely, so its\n * models/discriminators are not pulled into reachability and barrels/the client\n * never import a resource this run does not emit. The emitters additionally\n * consult `ctx.scopedServices` to emit only the selected services' per-service\n * resource/test files.\n */\nexport function generateAllFiles(spec: ApiSpec, emitter: Emitter, ctx: EmitterContext): GeneratedFile[] {\n  const scoped = !!ctx.scopedServices && ctx.scopedServices.size > 0;\n  const surfaceServices = aggregateSurfaceServices(spec, ctx);\n  // In a scoped run, restrict the blanket discriminated/event preservation to\n  // models reachable from the in-surface services; otherwise an out-of-scope,\n  // never-generated service's discriminated models (e.g. AgentRegistration*)\n  // would still be force-included and emit orphaned converters/variants.\n  // Webhooks are not a service, so no scope selects or excludes them: their\n  // payload models are in surface in every run, exactly as in a full one.\n  const referenced = collectReferencedNames(surfaceServices, spec.models, {\n    preserveAllDiscriminated: !scoped,\n    webhooks: spec.webhooks,\n  });\n  const reachableModels = spec.models.filter((m) => referenced.models.has(m.name));\n  const reachableEnums = spec.enums.filter((e) => referenced.enums.has(e.name));\n  const surfaceSpec: ApiSpec = { ...spec, services: surfaceServices };\n  const reachableSpec: ApiSpec = { ...surfaceSpec, models: reachableModels, enums: reachableEnums };\n\n  return [\n    ...emitter.generateModels(reachableModels, ctx),\n    ...emitter.generateEnums(reachableEnums, ctx),\n    ...emitter.generateResources(surfaceServices, ctx),\n    ...emitter.generateClient(surfaceSpec, ctx),\n    ...emitter.generateErrors(ctx),\n    ...(emitter.generateTypeSignatures?.(reachableSpec, ctx) ?? []),\n    ...emitter.generateTests(reachableSpec, ctx),\n  ];\n}\n\n/** Apply file header to generated files, respecting headerPlacement and JSON files. */\nexport function applyFileHeaders(files: GeneratedFile[], header: string): GeneratedFile[] {\n  return files.map((f) => ({\n    ...f,\n    content:\n      !header || f.path.endsWith('.json') || f.headerPlacement === 'skip' ? f.content : header + '\\n\\n' + f.content,\n    skipIfExists: f.skipIfExists ?? false,\n  }));\n}\n\nexport function generateFiles(\n  spec: ApiSpec,\n  emitter: Emitter,\n  options: {\n    namespace: string;\n    outputDir: string;\n    apiSurface?: ApiSurface;\n    overlayLookup?: OverlayLookup;\n    operationHints?: Record<string, OperationHint>;\n    mountRules?: Record<string, string>;\n    modelHints?: Record<string, string>;\n    emitterOptions?: Record<string, unknown>;\n    target?: string;\n    priorTargetManifestPaths?: Set<string>;\n    /** Scoped-generation signal (POST-MOUNT names); set on ctx for emitters to gate per-service emission. */\n    scopedServices?: Set<string>;\n    /** Canonical keys of services already on disk (prior manifest); narrows the scoped aggregate surface. */\n    presentServiceKeys?: Set<string>;\n  },\n): { files: GeneratedFile[]; ctx: EmitterContext; header: string; operations?: OperationsMap } {\n  const ctx = buildEmitterContext(spec, options);\n  const files = generateAllFiles(spec, emitter, ctx);\n  // Record operations for the SAME surface generateAllFiles emitted (scope ∪\n  // already-on-disk in a scoped run; the full spec otherwise). Recording a\n  // never-generated, out-of-scope service here would persist it into the merged\n  // manifest and make the next scoped run treat it as present — re-opening the\n  // orphan it was just kept out of.\n  const surfaceSpec: ApiSpec = { ...spec, services: aggregateSurfaceServices(spec, ctx) };\n  const operations = emitter.buildOperationsMap?.(surfaceSpec, ctx);\n  const header = emitter.fileHeader();\n  return { files: applyFileHeaders(files, header), ctx, header, operations };\n}\n","import * as fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { GeneratedFile } from './types.js';\nimport { writeFiles, type WriteResult } from './writer.js';\nimport { extractStatements } from './merger.js';\nimport { hasGrammar } from './merger.js';\n\n/**\n * Resolve a relative import path against a source file path to get the\n * target file path.  Handles implicit .ts extensions and /index.ts.\n */\nfunction resolveImportPath(\n  fromFilePath: string,\n  importModulePath: string,\n  knownPaths: Set<string>,\n): string | undefined {\n  // Strip quotes from module path key (tree-sitter keeps them)\n  const cleaned = importModulePath.replace(/^['\"]|['\"]$/g, '');\n  // Skip non-relative imports (node_modules, bare specifiers)\n  if (!cleaned.startsWith('.')) return undefined;\n\n  const dir = path.dirname(fromFilePath);\n  const resolved = path.normalize(path.join(dir, cleaned));\n\n  // Try exact match, .ts, /index.ts\n  for (const candidate of [resolved, `${resolved}.ts`, `${resolved}/index.ts`]) {\n    if (knownPaths.has(candidate)) return candidate;\n  }\n  return undefined;\n}\n\n/**\n * Determine whether a generated file is a \"root\" — a file that should always\n * be integrated into the target.  Roots are entry points from which we trace\n * the import graph.  Everything else must be reachable from a root.\n *\n * Roots: resource classes, client, config, errors, enums, barrel index files.\n * Non-roots: serializers, fixtures, standalone interfaces, test files.\n */\nfunction isRootFile(filePath: string): boolean {\n  // Fixtures are never roots (and should be filtered by integrateTarget already)\n  if (filePath.includes('/fixtures/')) return false;\n  // Test files are roots — they are standalone entry points that belong in the\n  // target repo even though nothing imports them.\n  if (filePath.endsWith('.spec.ts') || filePath.endsWith('.test.ts')) return true;\n  // Serializer files\n  if (filePath.includes('/serializers/')) return false;\n  // Standalone interface files (not barrel/index)\n  if (filePath.includes('/interfaces/') && !filePath.endsWith('/index.ts')) return false;\n  // Everything else is a root: resource classes, client, config, errors, enums, barrel files\n  return true;\n}\n\n/**\n * Build a file-level dependency graph from generated files and return only\n * files reachable from root entry points.  Uses tree-sitter to parse imports.\n */\nexport async function treeShakeFiles(files: GeneratedFile[], language: string): Promise<GeneratedFile[]> {\n  if (!hasGrammar(language)) return files;\n\n  const knownPaths = new Set(files.map((f) => f.path));\n\n  // Build dependency graph: file → set of files it imports\n  const deps = new Map<string, Set<string>>();\n  for (const file of files) {\n    // Only parse .ts/.js files (skip JSON, etc.)\n    if (!file.path.endsWith('.ts') && !file.path.endsWith('.js')) {\n      deps.set(file.path, new Set());\n      continue;\n    }\n    const parsed = await extractStatements(file.content, language);\n    const fileDeps = new Set<string>();\n    for (const imp of parsed.imports) {\n      const resolved = resolveImportPath(file.path, imp.key, knownPaths);\n      if (resolved) fileDeps.add(resolved);\n    }\n    // Also check re-export statements (export * from './foo')\n    for (const stmt of parsed.statements) {\n      if (stmt.kind === 'reexport') {\n        // Extract module path from \"export * from './foo'\" or \"export { X } from './foo'\"\n        const match = stmt.text.match(/from\\s+['\"]([^'\"]+)['\"]/);\n        if (match) {\n          const resolved = resolveImportPath(file.path, match[1], knownPaths);\n          if (resolved) fileDeps.add(resolved);\n        }\n      }\n    }\n    deps.set(file.path, fileDeps);\n  }\n\n  // Determine which file extensions are source code for this language\n  const codeExtensions = new Set([\n    '.ts',\n    '.js',\n    '.tsx',\n    '.jsx',\n    '.py',\n    '.rb',\n    '.go',\n    '.rs',\n    '.kt',\n    '.cs',\n    '.ex',\n    '.exs',\n    '.php',\n  ]);\n\n  // BFS from roots\n  const reachable = new Set<string>();\n  const queue: string[] = [];\n  for (const file of files) {\n    const ext = file.path.slice(file.path.lastIndexOf('.'));\n    // Non-code files (JSON, etc.) are always reachable — they can't participate\n    // in the import graph and are loaded at runtime (e.g. test fixtures).\n    if (!codeExtensions.has(ext)) {\n      reachable.add(file.path);\n      continue;\n    }\n    if (isRootFile(file.path)) {\n      reachable.add(file.path);\n      queue.push(file.path);\n    }\n  }\n  while (queue.length > 0) {\n    const current = queue.pop()!;\n    const fileDeps = deps.get(current);\n    if (!fileDeps) continue;\n    for (const dep of fileDeps) {\n      if (!reachable.has(dep)) {\n        reachable.add(dep);\n        queue.push(dep);\n      }\n    }\n  }\n\n  return files.filter((f) => reachable.has(f.path));\n}\n\nexport function mapFilesForTargetIntegration(files: GeneratedFile[], language: string): GeneratedFile[] {\n  const langPrefix = `${language}/`;\n  return files\n    .filter((f) => f.integrateTarget !== false) // integrateTarget: false files are standalone-only\n    .map((f) => {\n      const stripped = f.path.startsWith(langPrefix) ? f.path.replace(langPrefix, '') : f.path;\n      return {\n        ...f,\n        skipIfExists: false, // Always merge in target — never hard-skip\n        path: stripped,\n      };\n    });\n}\n\n/**\n * Resolve file-to-directory conflicts in the target.\n *\n * When a generated file creates a package directory (e.g., `api_keys/__init__.py`)\n * that would shadow an existing module file (e.g., `api_keys.py`), move the\n * module file's content into `_compat.py` inside the package and add a\n * re-export from `__init__.py`.  This preserves backward-compatible imports\n * (e.g., `from acme.api_keys import ApiKeysModule`) while the package directory\n * provides the generated models and resource classes.\n */\nasync function resolveFileToDirectoryConflicts(\n  files: GeneratedFile[],\n  targetDir: string,\n): Promise<{ files: GeneratedFile[]; removals: string[] }> {\n  const result = [...files];\n  const removals: string[] = [];\n\n  for (let i = 0; i < result.length; i++) {\n    const file = result[i];\n    // Match package init files: e.g., src/acme/api_keys/__init__.py\n    const match = file.path.match(/^(.+)\\/__init__\\.py$/);\n    if (!match) continue;\n\n    const dirPath = match[1]; // e.g., src/acme/api_keys\n    const moduleFilePath = `${dirPath}.py`; // e.g., src/acme/api_keys.py\n    const fullModulePath = path.join(targetDir, moduleFilePath);\n\n    let moduleContent: string;\n    try {\n      moduleContent = await fs.readFile(fullModulePath, 'utf-8');\n    } catch {\n      continue; // Module file doesn't exist — no conflict\n    }\n\n    // Create a compat shim inside the package with the old module's content\n    const compatPath = `${dirPath}/_compat.py`;\n    result.push({\n      path: compatPath,\n      content: moduleContent,\n      overwriteExisting: true,\n    });\n\n    // Append re-export from _compat to __init__.py so existing imports work.\n    // Compat must come AFTER generated models so hand-written types take\n    // precedence over generated types with the same name.\n    const compatImport = 'from ._compat import *  # noqa: F401,F403  # pyright: ignore[reportUnusedImport]';\n    const existingContent = file.content.endsWith('\\n') ? file.content : file.content + '\\n';\n    result[i] = {\n      ...file,\n      content: existingContent + compatImport + '\\n',\n    };\n\n    // Schedule the shadowed module file for removal\n    removals.push(fullModulePath);\n  }\n\n  return { files: result, removals };\n}\n\nexport interface IntegrateResult extends WriteResult {\n  /** Final set of paths this run claims ownership of in the target (post tree-shake + conflict resolution). */\n  emittedPaths: string[];\n}\n\nexport async function integrateGeneratedFiles(opts: {\n  files: GeneratedFile[];\n  language: string;\n  targetDir: string;\n  header: string;\n}): Promise<IntegrateResult> {\n  const mapped = mapFilesForTargetIntegration(opts.files, opts.language);\n  const shaken = await treeShakeFiles(mapped, opts.language);\n\n  // Handle file-to-directory conflicts before writing\n  const { files: resolved, removals } = await resolveFileToDirectoryConflicts(shaken, opts.targetDir);\n\n  const result = await writeFiles(resolved, opts.targetDir, {\n    language: opts.language,\n    header: opts.header,\n  });\n\n  // Remove shadowed module files after integration\n  for (const filePath of removals) {\n    try {\n      await fs.unlink(filePath);\n    } catch {\n      // File may already be gone\n    }\n  }\n\n  // The manifest tracks ALL files oagen owns, including tree-shaken ones.\n  // Tree-shaking decides what to write, but shaken files are still oagen-managed\n  // and must not be pruned from the target on subsequent runs.\n  return { ...result, emittedPaths: mapped.map((f) => f.path) };\n}\n","/**\n * Post-integration formatter.\n *\n * After generating and merging files into a target directory, runs the\n * emitter-provided format command on all written/merged files so that\n * generated code matches the target project's style conventions.\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport * as path from 'node:path';\nimport type { Emitter } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Run the emitter's format command on the given target files.\n * Silently skips if the emitter has no formatCommand or returns null.\n */\nexport async function formatTargetFiles(emitter: Emitter, targetDir: string, filePaths: string[]): Promise<void> {\n  if (filePaths.length === 0) return;\n  if (!emitter.formatCommand) return;\n\n  const formatCmd = emitter.formatCommand(targetDir);\n  if (!formatCmd) return;\n\n  const absolutePaths = filePaths.map((f) => path.resolve(targetDir, f));\n  const batchSize = formatCmd.batchSize ?? 100;\n\n  process.stderr.write(\n    `[oagen] formatting ${absolutePaths.length} file(s) with ${formatCmd.cmd} (batch ${batchSize})\\n`,\n  );\n\n  for (let i = 0; i < absolutePaths.length; i += batchSize) {\n    const batch = absolutePaths.slice(i, i + batchSize);\n    try {\n      await execFileAsync(formatCmd.cmd, [...formatCmd.args, ...batch], {\n        cwd: targetDir,\n        maxBuffer: 10 * 1024 * 1024,\n        timeout: 120_000,\n      });\n    } catch (err) {\n      // Formatter failed on this batch — continue with remaining batches.\n      // Surface the failure on stderr so misconfigured commands don't silently\n      // leave generated code unformatted every regen.\n      const msg = err instanceof Error ? err.message : String(err);\n      process.stderr.write(`[oagen] formatter batch failed: ${msg}\\n`);\n    }\n  }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { canonicalServiceKey } from './scoped-services.js';\n\n/**\n * Prune-manifest support for `oagen generate`.\n *\n * The manifest records every auto-generated file emitted on the previous run,\n * relative to the directory it lives in (either the `--output` standalone dir\n * or the `--target` integration dir).  On the next run we diff the previous\n * list against the current emission set and delete anything that's no longer\n * produced — preventing stale-file accumulation across regens.\n *\n * Design notes:\n *  - The manifest is versioned so future format changes can be handled safely.\n *  - Paths are stored sorted for deterministic diffs in git.\n *  - Deletion is gated on a header guard when one is available: we only remove\n *    files whose contents start with the auto-generated header.  This protects\n *    a hand-maintained file that happens to share a name with a previously\n *    generated one (extremely rare, but worth catching).\n *  - On first adoption (no previous manifest), pruning is skipped and a\n *    one-line notice is printed — no surprise deletions.\n */\n\nexport const MANIFEST_FILENAME = '.oagen-manifest.json';\nconst MANIFEST_VERSION = 2;\n\nexport interface Manifest {\n  /** Schema version.  Bump when the format changes incompatibly. */\n  version: number;\n  /** Emitter language (e.g. \"python\").  Used only as a consistency hint. */\n  language: string;\n  /** Human-readable or package-level SDK identity (e.g. \"acme-php\"). */\n  sdkName?: string;\n  /** SHA-256 hash of the source OpenAPI spec used for generation. */\n  specSha?: string;\n  /** Path or reference to the source spec. */\n  specPath?: string;\n  /** Git SHA or version of the emitter code used. */\n  emitterSha?: string;\n  /** Emitter version string if available. */\n  emitterVersion?: string;\n  /** SHA-256 hash of the effective oagen.config.ts after resolution. */\n  configSha?: string;\n  /** Version of the compat snapshot/report schema expected by this generation. */\n  compatSchemaVersion?: string;\n  /** Sorted list of paths, relative to the manifest's containing directory. */\n  files: string[];\n  /** Maps \"METHOD /path\" to SDK method + service property name. */\n  operations?: Record<string, unknown>;\n}\n\nexport interface PruneResult {\n  /** Paths actually deleted. */\n  pruned: string[];\n  /** Paths skipped because the header guard didn't match (preserved). */\n  preserved: string[];\n  /** Paths already absent on disk (nothing to do). */\n  missing: string[];\n}\n\n/** Read `.oagen-manifest.json` from a directory.  Returns null if absent or malformed. */\nexport async function readManifest(dir: string): Promise<Manifest | null> {\n  const manifestPath = path.join(dir, MANIFEST_FILENAME);\n  let raw: string;\n  try {\n    raw = await fs.readFile(manifestPath, 'utf-8');\n  } catch {\n    return null;\n  }\n  try {\n    const parsed = JSON.parse(raw) as Partial<Manifest>;\n    if (\n      typeof parsed.version !== 'number' ||\n      typeof parsed.language !== 'string' ||\n      !Array.isArray(parsed.files) ||\n      !parsed.files.every((p): p is string => typeof p === 'string')\n    ) {\n      return null;\n    }\n    if (parsed.version > MANIFEST_VERSION) {\n      console.warn(\n        `[oagen] ${MANIFEST_FILENAME} schema version ${parsed.version} is newer than supported (${MANIFEST_VERSION}); ignoring for pruning.`,\n      );\n      return null;\n    }\n    // v1 manifests are forward-compatible — new fields are simply absent\n    return parsed as Manifest;\n  } catch {\n    return null;\n  }\n}\n\n/** Options for writing a manifest. */\nexport interface WriteManifestOpts {\n  language: string;\n  files: Iterable<string>;\n  sdkName?: string;\n  specSha?: string;\n  specPath?: string;\n  emitterSha?: string;\n  emitterVersion?: string;\n  configSha?: string;\n  compatSchemaVersion?: string;\n  operations?: Record<string, unknown>;\n}\n\n/** Write `.oagen-manifest.json` to a directory with sorted paths. */\nexport async function writeManifest(dir: string, opts: WriteManifestOpts): Promise<void> {\n  const manifestPath = path.join(dir, MANIFEST_FILENAME);\n  const manifest: Manifest = {\n    version: MANIFEST_VERSION,\n    language: opts.language,\n    ...(opts.sdkName !== undefined ? { sdkName: opts.sdkName } : {}),\n    ...(opts.specSha !== undefined ? { specSha: opts.specSha } : {}),\n    ...(opts.specPath !== undefined ? { specPath: opts.specPath } : {}),\n    ...(opts.emitterSha !== undefined ? { emitterSha: opts.emitterSha } : {}),\n    ...(opts.emitterVersion !== undefined ? { emitterVersion: opts.emitterVersion } : {}),\n    ...(opts.configSha !== undefined ? { configSha: opts.configSha } : {}),\n    ...(opts.compatSchemaVersion !== undefined ? { compatSchemaVersion: opts.compatSchemaVersion } : {}),\n    files: [...new Set(opts.files)].sort(),\n    ...(opts.operations !== undefined ? { operations: opts.operations } : {}),\n  };\n  await fs.mkdir(dir, { recursive: true });\n  await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n}\n\n/** Return the set of previous paths no longer present in the current emission. */\nexport function computeStalePaths(prev: Manifest, currentPaths: Iterable<string>): string[] {\n  const current = new Set(currentPaths);\n  return prev.files.filter((p) => !current.has(p)).sort();\n}\n\n/**\n * Merge a scoped run's emitted records into the prior manifest's records.\n *\n * A scoped (`--services`) run only emits files for the selected services, but it\n * must NOT discard the prior manifest's record of unselected services' files\n * records. The result unions prior + scoped file paths and shallow-merges the\n * operations maps, with scoped operations overriding prior entries for the same\n * \"METHOD /path\" key (a re-emission updates that operation's record).\n *\n * When `prev` is null (the first-ever run is scoped) there is nothing to\n * preserve, so the scoped subset is returned unchanged — matching the\n * first-adoption behavior of a full run.\n */\nexport function mergeScopedManifestRecords(\n  prev: Manifest | null,\n  scopedFiles: Iterable<string>,\n  scopedOperations?: Record<string, unknown>,\n): { files: string[]; operations?: Record<string, unknown> } {\n  const scopedFileList = [...scopedFiles];\n  if (!prev) {\n    return { files: scopedFileList, operations: scopedOperations };\n  }\n  const files = [...new Set([...prev.files, ...scopedFileList])].sort();\n  const priorOps = prev.operations;\n  const operations = priorOps || scopedOperations ? { ...priorOps, ...scopedOperations } : undefined;\n  return { files, operations };\n}\n\n/**\n * Extract the set of services a prior manifest records as already generated on\n * disk, as canonical (casing/separator-insensitive) keys.\n *\n * The manifest's `operations` map carries each operation's owning `service`\n * (snake_case for most emitters, camelCase for Kotlin). A scoped (`--services`)\n * run uses this to tell \"service in the spec that is already on disk\" apart from\n * \"service the spec just added that this SDK has never generated\" — only the\n * former may be wired into aggregate/barrel/client files alongside the\n * selection, so a brand-new out-of-scope service is never referenced by files\n * whose implementation this run does not emit.\n *\n * Returns an empty set when the manifest is null or carries no operations\n * (a legacy manifest with no operations data); callers treat that as \"present\n * set unknown\" and fall back to not narrowing the surface.\n */\nexport function manifestServiceKeys(manifest: Manifest | null): Set<string> {\n  const keys = new Set<string>();\n  const ops = manifest?.operations;\n  if (!ops) return keys;\n  for (const value of Object.values(ops)) {\n    const entries = Array.isArray(value) ? value : [value];\n    for (const entry of entries) {\n      const service = (entry as { service?: unknown } | null)?.service;\n      if (typeof service === 'string' && service.length > 0) {\n        keys.add(canonicalServiceKey(service));\n      }\n    }\n  }\n  return keys;\n}\n\n/**\n * Delete stale files from `dir`.\n *\n * When `header` is provided, a file is only deleted if its contents start with\n * that header — so hand-maintained files that somehow collide with a previously\n * generated path can't be clobbered.  When `header` is omitted, the guard is\n * skipped (useful for non-source artifacts like fixture JSON).\n *\n * Returns lists for reporting.  Empty parent directories are removed after\n * deletion, up to (but not including) `dir` itself.\n */\nexport async function pruneStaleFiles(\n  dir: string,\n  paths: string[],\n  opts: { header?: string } = {},\n): Promise<PruneResult> {\n  const pruned: string[] = [];\n  const preserved: string[] = [];\n  const missing: string[] = [];\n\n  for (const relPath of paths) {\n    const fullPath = path.join(dir, relPath);\n    let content: string;\n    try {\n      content = await fs.readFile(fullPath, 'utf-8');\n    } catch {\n      missing.push(relPath);\n      continue;\n    }\n    if (opts.header && !content.startsWith(opts.header)) {\n      preserved.push(relPath);\n      continue;\n    }\n    try {\n      await fs.unlink(fullPath);\n      pruned.push(relPath);\n    } catch {\n      // Racing deletion or permission issue — treat as missing rather than fatal.\n      missing.push(relPath);\n      continue;\n    }\n    await removeEmptyParents(path.dirname(fullPath), dir);\n  }\n\n  return { pruned, preserved, missing };\n}\n\n/**\n * Walk up from `startDir` removing empty directories until we hit `stopDir`\n * (exclusive) or a non-empty directory.  Silently ignores errors.\n */\nasync function removeEmptyParents(startDir: string, stopDir: string): Promise<void> {\n  let current = path.resolve(startDir);\n  const stop = path.resolve(stopDir);\n  while (current.startsWith(stop + path.sep) && current !== stop) {\n    let entries: string[];\n    try {\n      entries = await fs.readdir(current);\n    } catch {\n      return;\n    }\n    if (entries.length > 0) return;\n    try {\n      await fs.rmdir(current);\n    } catch {\n      return;\n    }\n    current = path.dirname(current);\n  }\n}\n","import type { ApiSpec } from '../ir/types.js';\nimport { validateModelHints } from '../ir/types.js';\nimport type { OperationHint } from '../ir/operation-hints.js';\nimport type { Emitter, GeneratedFile } from './types.js';\nimport type { ApiSurface, OverlayLookup } from '../compat/types.js';\nimport { writeFiles } from './writer.js';\nimport { generateFiles } from './generate-files.js';\nimport { resolveScopedServices } from './scoped-services.js';\nimport { integrateGeneratedFiles } from './integrate.js';\nimport { formatTargetFiles } from './formatter.js';\nimport {\n  computeStalePaths,\n  manifestServiceKeys,\n  MANIFEST_FILENAME,\n  mergeScopedManifestRecords,\n  pruneStaleFiles,\n  readManifest,\n  writeManifest,\n} from './manifest.js';\n\nexport async function generate(\n  spec: ApiSpec,\n  emitter: Emitter,\n  options: {\n    namespace: string;\n    dryRun?: boolean;\n    outputDir: string;\n    target?: string;\n    apiSurface?: ApiSurface;\n    overlayLookup?: OverlayLookup;\n    operationHints?: Record<string, OperationHint>;\n    mountRules?: Record<string, string>;\n    modelHints?: Record<string, string>;\n    emitterOptions?: Record<string, unknown>;\n    /** When true, skip deletion of files recorded in the previous manifest but not in the current emission. */\n    noPrune?: boolean;\n    /**\n     * Post-mount service names to generate (a `--services` run). When non-empty,\n     * the FULL spec is still emitted for models/enums/client/barrels (so shared\n     * files stay byte-identical and a brand-new selected service is wired into the\n     * client automatically); only per-service resource/test emission is gated to\n     * the selection (via `ctx.scopedServices`). Pruning is disabled and the\n     * manifest is merged so unselected services' records survive.\n     */\n    services?: string[];\n  },\n): Promise<GeneratedFile[]> {\n  // Fail loud on modelHints typos up front, against the FULL spec. Placement\n  // (assignModelsToServices) is intentionally lenient because it runs over\n  // partial model/service slices; this single check is where typos are caught,\n  // and it stays correct in scoped runs because the spec is not filtered.\n  if (options.modelHints) {\n    validateModelHints(spec.models, spec.services, options.modelHints);\n  }\n\n  // Scoped generation: validate + expand the selection to POST-MOUNT names. The\n  // spec is NOT filtered — placement/dedup/shared-schemas are computed over the\n  // full spec so shared files stay byte-identical; emitters gate only per-service\n  // resource/test emission on this set.\n  const scopedServices =\n    options.services && options.services.length > 0\n      ? resolveScopedServices(spec, options.services, options.mountRules)\n      : undefined;\n  const scoped = scopedServices !== undefined;\n  // Scoped mode implies no-prune so unselected services' files survive.\n  const noPrune = options.noPrune === true || scoped;\n\n  // Read previous manifests up front so emitters can mark files the prior run\n  // wrote as safe-to-overwrite (vs files a human hand-maintains), and so scoped\n  // runs can merge prior records. Skipped only when --no-prune is set on a\n  // non-scoped run (opting out of lifecycle tracking). Scoped runs always read,\n  // even though they force no-prune, because the merge needs the prior records.\n  const skipManifestRead = options.noPrune === true && !scoped;\n  const outputPrevManifestForCtx = skipManifestRead ? null : await readManifest(options.outputDir);\n  const targetManifestForCtx = options.target && !skipManifestRead ? await readManifest(options.target) : null;\n  const priorManifestForCtx = targetManifestForCtx ?? outputPrevManifestForCtx;\n  const priorTargetManifestPaths = priorManifestForCtx ? new Set(priorManifestForCtx.files) : undefined;\n  // Services already generated on disk (from the prior manifest's operations).\n  // Only consulted in a scoped run: it keeps already-present services in the\n  // aggregate/barrel/client surface (byte-identical regen) while excluding a\n  // service the spec just added that this SDK has never generated — which would\n  // otherwise be wired into the client/barrels with no implementation behind it.\n  const presentServiceKeys = scoped ? manifestServiceKeys(priorManifestForCtx) : undefined;\n\n  const {\n    files: withHeaders,\n    header,\n    operations,\n  } = generateFiles(spec, emitter, {\n    ...options,\n    priorTargetManifestPaths,\n    scopedServices,\n    presentServiceKeys,\n  });\n\n  if (options.dryRun) {\n    if (options.target) {\n      console.log(`\\nTarget integration (${options.target}):`);\n      for (const f of withHeaders) {\n        console.log(`  ${f.path}`);\n      }\n    }\n    return withHeaders;\n  }\n\n  // Reuse the manifest read before generation; nothing above writes it.\n  const outputPrevManifest = outputPrevManifestForCtx;\n\n  const writeResult = await writeFiles(withHeaders, options.outputDir, {\n    language: emitter.language,\n    header,\n  });\n\n  if (writeResult.merged.length > 0) {\n    console.log(`Merged into ${writeResult.merged.length} existing files (additive only)`);\n  }\n  if (writeResult.ignored.length > 0) {\n    console.log(`Ignored ${writeResult.ignored.length} files (@oagen-ignore-file)`);\n  }\n\n  const outputEmittedPaths = withHeaders.map((f) => f.path);\n  await applyManifestPrune({\n    dir: options.outputDir,\n    label: 'Output',\n    prevManifest: outputPrevManifest,\n    currentPaths: outputEmittedPaths,\n    language: emitter.language,\n    header,\n    noPrune,\n    operations,\n    scoped,\n  });\n\n  // Format output files so the emitter's formatter runs even without --target.\n  const allOutputFiles = [...writeResult.written, ...writeResult.merged];\n  if (allOutputFiles.length > 0) {\n    await formatTargetFiles(emitter, options.outputDir, allOutputFiles);\n  }\n\n  // Target integration pass\n  if (options.target) {\n    // Reuse the manifest we already read to build the emitter context.  This\n    // is correct because nothing between the two reads writes the manifest.\n    const targetPrevManifest = targetManifestForCtx;\n\n    const targetResult = await integrateGeneratedFiles({\n      files: withHeaders,\n      language: emitter.language,\n      targetDir: options.target,\n      header,\n    });\n\n    if (targetResult.written.length > 0) {\n      console.log(`Target: created ${targetResult.written.length} new files`);\n    }\n    if (targetResult.merged.length > 0) {\n      console.log(`Target: merged into ${targetResult.merged.length} existing files (additive only)`);\n    }\n    if (targetResult.skipped.length > 0) {\n      console.log(`Target: skipped ${targetResult.skipped.length} files (excluded or no grammar)`);\n    }\n\n    await applyManifestPrune({\n      dir: options.target,\n      label: 'Target',\n      prevManifest: targetPrevManifest,\n      currentPaths: targetResult.emittedPaths,\n      language: emitter.language,\n      header,\n      noPrune,\n      operations,\n      scoped,\n    });\n\n    // Run the emitter's formatter on all written/merged/identical files\n    const allTargetFiles = [...targetResult.written, ...targetResult.merged, ...targetResult.identical];\n    if (allTargetFiles.length > 0) {\n      await formatTargetFiles(emitter, options.target, allTargetFiles);\n    }\n  }\n\n  return withHeaders;\n}\n\n/**\n * Prune files recorded in the previous manifest but absent from the current emission,\n * then write the fresh manifest.  Safe on first adoption (no previous manifest).\n */\nasync function applyManifestPrune(opts: {\n  dir: string;\n  label: string;\n  prevManifest: Awaited<ReturnType<typeof readManifest>>;\n  currentPaths: string[];\n  language: string;\n  header: string;\n  noPrune?: boolean;\n  operations?: Record<string, unknown>;\n  /** When true, union this scoped run's records with the prior manifest. */\n  scoped?: boolean;\n}): Promise<void> {\n  // A scoped run only emits the selected services' files, so the manifest is\n  // merged with the prior records rather than replaced — otherwise unselected\n  // services would be dropped from the manifest and mis-pruned on the next run.\n  const records = opts.scoped\n    ? mergeScopedManifestRecords(opts.prevManifest, opts.currentPaths, opts.operations)\n    : { files: opts.currentPaths, operations: opts.operations };\n  const manifestOpts = { language: opts.language, files: records.files, operations: records.operations };\n  if (opts.noPrune) {\n    // Still refresh the manifest so future runs with pruning enabled have a baseline.\n    await writeManifest(opts.dir, manifestOpts);\n    return;\n  }\n\n  if (!opts.prevManifest) {\n    console.log(\n      `${opts.label}: no ${MANIFEST_FILENAME} found — skipping prune (this baseline manifest will be written now).`,\n    );\n    await writeManifest(opts.dir, manifestOpts);\n    return;\n  }\n\n  const stale = computeStalePaths(opts.prevManifest, opts.currentPaths);\n  if (stale.length > 0) {\n    const { pruned, preserved } = await pruneStaleFiles(opts.dir, stale, { header: opts.header });\n    if (pruned.length > 0) {\n      console.log(`${opts.label}: pruned ${pruned.length} stale file${pruned.length === 1 ? '' : 's'}`);\n    }\n    if (preserved.length > 0) {\n      console.log(\n        `${opts.label}: preserved ${preserved.length} file${preserved.length === 1 ? '' : 's'} in previous manifest but lacking the auto-generated header (possibly hand-edited).`,\n      );\n      for (const p of preserved) console.log(`  ${p}`);\n    }\n  }\n\n  await writeManifest(opts.dir, manifestOpts);\n}\n","import { RegistryError } from '../errors.js';\nimport type { Emitter } from './types.js';\n\nconst emitters = new Map<string, Emitter>();\n\nexport function registerEmitter(emitter: Emitter): void {\n  emitters.set(emitter.language, emitter);\n}\n\nexport function getEmitter(language: string): Emitter {\n  const emitter = emitters.get(language);\n  if (!emitter) {\n    const available = [...emitters.keys()].join(', ') || '(none)';\n    throw new RegistryError(\n      `Unknown language: ${language}. Available: ${available}`,\n      `Register an emitter for \"${language}\" via registerEmitter() or check your oagen.config.ts plugin configuration.`,\n    );\n  }\n  return emitter;\n}\n","import { isDeepStrictEqual } from 'node:util';\nimport type { Extensions, Operation } from '../ir/types.js';\nimport type { ModelDirection } from './direction.js';\nimport type { FieldChange, ParamChange, RequestBodyEncoding, ResponseHeaderChange } from './types.js';\n\n/**\n * Whether an IR node is deprecated. The parser only ever writes `true` and\n * leaves the key absent otherwise, so `undefined` and an explicit `false` are\n * the same thing here: not deprecated.\n */\nexport function isDeprecated(node: { deprecated?: boolean }): boolean {\n  return node.deprecated === true;\n}\n\n/** The `details` of a `*-deprecated-changed` entry, read old → new. */\nexport function deprecationDetails(nowDeprecated: boolean): string {\n  return nowDeprecated ? 'live → deprecated' : 'deprecated → live';\n}\n\n/** The two sides of a `deprecated` flip, carried on the change that reports it. */\nexport interface DeprecationFlip {\n  oldDeprecated: boolean;\n  newDeprecated: boolean;\n}\n\n/**\n * `{ oldDeprecated, newDeprecated }` when the flag differs between the two\n * nodes, `undefined` when it does not. The differ spreads it onto the owning\n * change, so the direction travels with the change and the `behaviorChanges`\n * mirror never has to look the node up again.\n */\nexport function deprecationFlip(\n  oldNode: { deprecated?: boolean },\n  newNode: { deprecated?: boolean },\n): DeprecationFlip | undefined {\n  const oldDeprecated = isDeprecated(oldNode);\n  const newDeprecated = isDeprecated(newNode);\n  return oldDeprecated === newDeprecated ? undefined : { oldDeprecated, newDeprecated };\n}\n\n/** The two sides of a parameter's name, carried on the `param-name-changed` entry that reports it. */\nexport interface ParameterNameShift {\n  /** The name as the old spec wrote it (`X-Pet-Token`). */\n  oldName: string;\n  /** The name as the new spec writes it (`x-pet-token`). */\n  newName: string;\n  /** `name X-Pet-Token → x-pet-token`. */\n  details: string;\n}\n\n/**\n * `{ oldName, newName, details }` when two parameters the differ paired\n * are not written the same, `undefined` when they are. Parameters are\n * paired on `parameterKey`, which folds a header's name and nothing else,\n * so the only pairing whose two names differ is a header whose name\n * changed case alone (`X-Pet-Token` → `x-pet-token`): the same header on\n * the wire (RFC 9110 §5.1), still accepted with the same type and\n * requiredness, hence additive at the IR layer — an emitter that derives an\n * identifier from the name as written may still rename it, which its own\n * compat check reports, as it does for `param-format-changed` (#295).\n * A response header pairs on `foldHeaderName` the same way, so its\n * respelling is read through this function too (`header-name-changed`).\n */\nexport function parameterNameShift(\n  oldParam: { name: string },\n  newParam: { name: string },\n): ParameterNameShift | undefined {\n  if (oldParam.name === newParam.name) return undefined;\n  return {\n    oldName: oldParam.name,\n    newName: newParam.name,\n    details: `name ${oldParam.name} → ${newParam.name}`,\n  };\n}\n\n/** The two sides of a `tags` change, carried on the change that reports it. */\nexport interface TagsShift {\n  /** The node's `tags` in the old spec, in document order; `[]` when it carried none. */\n  oldTags: string[];\n  /** The node's `tags` in the new spec, in document order; `[]` when it carries none. */\n  newTags: string[];\n}\n\n/**\n * `{ oldTags, newTags }` when a node's `tags` differ between the two specs,\n * `undefined` when they do not. The lists are compared in document order,\n * entry by entry, since the first tag is what the parser names an\n * operation's service from; an absent key is an empty list.\n */\nexport function tagsShift(oldNode: { tags?: string[] }, newNode: { tags?: string[] }): TagsShift | undefined {\n  const oldTags = oldNode.tags ?? [];\n  const newTags = newNode.tags ?? [];\n  const same = oldTags.length === newTags.length && oldTags.every((tag, i) => tag === newTags[i]);\n  return same ? undefined : { oldTags, newTags };\n}\n\n/** The two sides of an `extensions` change, carried on the change that reports it; each side present only when the node had extensions there. */\nexport interface ExtensionsShift {\n  oldExtensions?: Extensions;\n  newExtensions?: Extensions;\n}\n\n/** A node's `extensions` as compared: an absent key and an empty object both read as none. */\nfunction declaredExtensions(node: { extensions?: Extensions }): Extensions | undefined {\n  const { extensions } = node;\n  return extensions !== undefined && Object.keys(extensions).length > 0 ? extensions : undefined;\n}\n\n/**\n * `{ oldExtensions?, newExtensions? }` when a node's `extensions` differ\n * between the two specs — a key added, removed or given another value,\n * compared deeply (`isDeepStrictEqual`), key order aside — `undefined` when\n * they do not. An absent key and an empty object are the same thing: the\n * parser leaves the key absent when a node declares no extension. The\n * differ spreads the result onto the owning change, as it does a\n * deprecation flip, so the `behaviorChanges` mirror never looks the node up\n * again; a side the node had no extensions on is left absent.\n */\nexport function extensionsShift(\n  oldNode: { extensions?: Extensions },\n  newNode: { extensions?: Extensions },\n): ExtensionsShift | undefined {\n  const oldExtensions = declaredExtensions(oldNode);\n  const newExtensions = declaredExtensions(newNode);\n  if (isDeepStrictEqual(oldExtensions, newExtensions)) return undefined;\n  return {\n    ...(oldExtensions ? { oldExtensions } : {}),\n    ...(newExtensions ? { newExtensions } : {}),\n  };\n}\n\n/** The two sides of a `requestBodyEncoding` change, carried on the change that reports it. */\nexport interface RequestBodyEncodingShift {\n  /** The node's `requestBodyEncoding` in the old spec; `undefined` when its body carried none. */\n  oldRequestBodyEncoding: RequestBodyEncoding | undefined;\n  /** The node's `requestBodyEncoding` in the new spec; `undefined` when its body carries none. */\n  newRequestBodyEncoding: RequestBodyEncoding | undefined;\n}\n\n/**\n * `{ oldRequestBodyEncoding, newRequestBodyEncoding }` when a node's\n * `requestBodyEncoding` differs between the two specs while both carry a\n * `requestBody`, `undefined` otherwise. The encoding is the wire format the\n * body is serialized as (`json`, `form-data`, `form-urlencoded`, `binary`,\n * `text`), read from the media type the body is declared under. A body\n * appearing or disappearing takes its encoding with it and is the body\n * change's to report (`requestBodyChanged` on an operation, `payload added`\n * / `payload removed` on a webhook), so neither change kind carries the two\n * sides for it. An absent encoding beside a body is compared as a value of\n * its own, so a body that gained or lost one is a change too. Whether a\n * change breaks is the caller's rule — `diffOperations` and\n * `diffWebhookBody` read it off the media types each side declares\n * (`ownRepresentationKept`): an SDK built for the old spec keeps sending\n * the old representation, and a handler built for it keeps decoding what\n * it declared. Both read the encoding through this function, so an\n * operation's body and a webhook's payload are judged alike.\n */\nexport function requestBodyEncodingShift(\n  oldNode: { requestBody?: Operation['requestBody']; requestBodyEncoding?: RequestBodyEncoding },\n  newNode: { requestBody?: Operation['requestBody']; requestBodyEncoding?: RequestBodyEncoding },\n): RequestBodyEncodingShift | undefined {\n  if (!oldNode.requestBody || !newNode.requestBody) return undefined;\n  const oldRequestBodyEncoding = oldNode.requestBodyEncoding;\n  const newRequestBodyEncoding = newNode.requestBodyEncoding;\n  return oldRequestBodyEncoding === newRequestBodyEncoding\n    ? undefined\n    : { oldRequestBodyEncoding, newRequestBodyEncoding };\n}\n\n/** The `details` a webhook change reports an encoding shift with: `encoding json → form-urlencoded`, `<none>` for no encoding. */\nexport function requestBodyEncodingDetails(shift: RequestBodyEncodingShift): string {\n  return `encoding ${shift.oldRequestBodyEncoding ?? '<none>'} → ${shift.newRequestBodyEncoding ?? '<none>'}`;\n}\n\nexport function classifyFieldChange(\n  kind: FieldChange['kind'],\n  fieldName: string,\n  isRequired?: boolean,\n  // Which side of the wire the owning model is used on. Defaults to `unknown`,\n  // which keeps the conservative direction-blind classification for callers that\n  // have no model-usage index to hand.\n  direction: ModelDirection = 'unknown',\n): FieldChange {\n  switch (kind) {\n    case 'field-added':\n      // Requiredness binds callers on the request side only: they must supply\n      // every required request field, but they only *read* responses. So a new\n      // required field on a response-only model is additive — the server simply\n      // always sends it, and existing caller code keeps compiling and\n      // deserializing. Request-facing, both-facing, and unknown-direction models\n      // keep the breaking classification.\n      if (isRequired && direction === 'response') {\n        return {\n          kind,\n          fieldName,\n          classification: 'additive',\n          details: 'required on a response-only model',\n        };\n      }\n      return {\n        kind,\n        fieldName,\n        classification: isRequired ? 'breaking' : 'additive',\n      };\n    case 'field-removed':\n      return { kind, fieldName, classification: 'breaking' };\n    case 'field-type-changed':\n      return { kind, fieldName, classification: 'breaking' };\n    case 'field-format-changed':\n      // A primitive's `format` changing (e.g., string → string format=email)\n      // is classified additive at the IR level: the wire-format base type is\n      // unchanged, so callers' deserialization keeps working. Per-emitter\n      // compat checks catch any source-level break a specific language layers\n      // on top (e.g., a typed Email value object in TypeScript).\n      return { kind, fieldName, classification: 'additive' };\n    case 'field-required-changed':\n      return {\n        kind,\n        fieldName,\n        classification: isRequired ? 'breaking' : 'additive',\n        details: isRequired ? 'optional → required' : 'required → optional',\n      };\n    case 'field-access-changed':\n      return { kind, fieldName, classification: 'breaking' };\n    case 'field-deprecated-changed':\n      // Deprecation changes no contract: the field is still there with the\n      // same type and requiredness, whichever way the flag went. The caller\n      // attaches `details` saying which way (see `deprecationDetails`).\n      return { kind, fieldName, classification: 'additive' };\n    case 'field-extensions-changed':\n      // Extensions are not shape: the field is still there with the same\n      // type and requiredness. The caller spreads the two sides on\n      // (`extensionsShift`).\n      return { kind, fieldName, classification: 'additive' };\n  }\n}\n\n/**\n * Classify a change to a header a response declares, from the reader's side:\n * the SDK reads the header off the response and never sends it, so the rules\n * are the ones `diffWebhookParams` applies to a webhook's parameters, not\n * `classifyParamChange`'s request-side ones.\n *\n * - added: additive, required or not — the server simply starts sending it.\n * - removed: breaking — an accessor the SDK exposed has nothing to read.\n * - type changed: breaking; format-only changes are additive, as elsewhere.\n * - optional → required: additive (now always present);\n *   required → optional: breaking (code that assumed presence breaks).\n * - name respelled (case only, since that is all a pair can differ by):\n *   additive — an emitter may derive an identifier from the name as written.\n * - deprecated flipped: additive either way — the header is still sent with\n *   the same type and requiredness.\n *\n * `isRequired` is read for `header-required-changed` only: the new side's\n * flag. The caller attaches the `details` and sides the kind carries.\n */\nexport function classifyResponseHeaderChange(\n  kind: ResponseHeaderChange['kind'],\n  headerName: string,\n  isRequired?: boolean,\n): ResponseHeaderChange {\n  switch (kind) {\n    case 'header-added':\n      return { kind, headerName, classification: 'additive' };\n    case 'header-removed':\n      return { kind, headerName, classification: 'breaking' };\n    case 'header-type-changed':\n      return { kind, headerName, classification: 'breaking' };\n    case 'header-format-changed':\n      return { kind, headerName, classification: 'additive' };\n    case 'header-required-changed':\n      return {\n        kind,\n        headerName,\n        classification: isRequired ? 'additive' : 'breaking',\n        details: isRequired ? 'optional → required' : 'required → optional',\n      };\n    case 'header-name-changed':\n      return { kind, headerName, classification: 'additive' };\n    case 'header-deprecated-changed':\n      return { kind, headerName, classification: 'additive' };\n  }\n}\n\nexport function classifyParamChange(kind: ParamChange['kind'], paramName: string, isRequired?: boolean): ParamChange {\n  switch (kind) {\n    case 'param-added':\n      return {\n        kind,\n        paramName,\n        classification: isRequired ? 'breaking' : 'additive',\n      };\n    case 'param-removed':\n      return { kind, paramName, classification: 'breaking' };\n    case 'param-type-changed':\n      return { kind, paramName, classification: 'breaking' };\n    case 'param-format-changed':\n      // See `field-format-changed`: format-only diffs are additive at the IR\n      // layer.\n      return { kind, paramName, classification: 'additive' };\n    case 'param-required-changed':\n      return {\n        kind,\n        paramName,\n        classification: isRequired ? 'breaking' : 'additive',\n      };\n    case 'param-default-changed':\n      // Removing or changing a default that callers may have implicitly relied on\n      // changes runtime behavior for clients who never set the param explicitly.\n      // We treat this as breaking so it surfaces as a major bump rather than\n      // sliding through as a silent regression.\n      return { kind, paramName, classification: 'breaking' };\n    case 'param-deprecated-changed':\n      // See `field-deprecated-changed`: the parameter is still accepted with\n      // the same type and requiredness, so this is additive either way.\n      return { kind, paramName, classification: 'additive' };\n    case 'param-name-changed':\n      // See `parameterNameShift`: only a header's case can differ between\n      // two paired parameters, and the wire reads it the same, so this is\n      // additive at the IR layer like `param-format-changed`.\n      return { kind, paramName, classification: 'additive' };\n    case 'param-content-type-changed':\n      // See `parameterContentTypeShift`: the media type decides how the value\n      // is serialized (JSON-encoded under `application/json`, by style and\n      // explode under `schema`), so a caller encoding it the old way sends a\n      // value the API no longer reads — breaking in both directions, like a\n      // type change.\n      return { kind, paramName, classification: 'breaking' };\n  }\n}\n","import type { ApiSpec, Model, TypeRef } from '../ir/types.js';\nimport {\n  collectResponseHeaders,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectWebhookTypeRefs,\n} from '../ir/types.js';\n\n/**\n * Which side of the wire a model sits on, from the caller's point of view.\n *\n * Requiredness only binds callers on the request side — they must construct\n * every required request field, but they only ever *read* responses. The differ\n * needs that distinction before it can call a newly-required field breaking.\n */\nexport type ModelDirection = 'request' | 'response' | 'both' | 'unknown';\n\nexport type DirectionIndex = ReadonlyMap<string, ModelDirection>;\n\n/**\n * Classify every model in `specs` as request-facing, response-facing, both, or\n * unknown.\n *\n * Pass both the baseline and the candidate spec: a model that was request-facing\n * in either one keeps its request direction for the whole diff, so a schema that\n * moves request → response mid-release doesn't get that release's requiredness\n * changes silently downgraded.\n *\n * Models reachable from neither side (unreferenced schemas, or a spec whose\n * operations weren't supplied) stay `unknown`, which preserves the conservative\n * pre-direction classification.\n */\nexport function buildDirectionIndex(...specs: ApiSpec[]): DirectionIndex {\n  const models = new Map<string, Model>();\n  for (const spec of specs) {\n    for (const model of spec.models) if (!models.has(model.name)) models.set(model.name, model);\n  }\n\n  const requestSeeds: TypeRef[] = [];\n  const responseSeeds: TypeRef[] = [];\n\n  for (const spec of specs) {\n    for (const service of spec.services) {\n      for (const op of service.operations) {\n        if (op.requestBody) requestSeeds.push(op.requestBody);\n        // A body the caller may send under another media type is constructed\n        // by the caller just the same, so it is request-facing too.\n        for (const { type } of collectRequestBodyTypes(op)) requestSeeds.push(type);\n        // Parameters are caller-supplied too, so a model reached through one is\n        // request-facing even when the operation has no body.\n        for (const param of [\n          ...op.pathParams,\n          ...op.queryParams,\n          ...(op.bodyOwnedQueryParams ?? []),\n          ...op.headerParams,\n          ...(op.cookieParams ?? []),\n        ]) {\n          requestSeeds.push(param.type);\n        }\n        responseSeeds.push(op.response);\n        // The iterator yields its item type, which an explicit `dataPath` can\n        // point at a model `response` does not reach.\n        if (op.pagination) responseSeeds.push(op.pagination.itemType);\n        for (const field of op.pagination?.envelopeFields ?? []) responseSeeds.push(field.type);\n        for (const header of collectResponseHeaders(op)) responseSeeds.push(header.type);\n        for (const { type } of collectResponseBodyTypes(op)) responseSeeds.push(type);\n        for (const success of op.successResponses ?? []) responseSeeds.push(success.type);\n        for (const error of op.errors) if (error.type) responseSeeds.push(error.type);\n      }\n    }\n    // A webhook's payload and parameters are received, never constructed, by\n    // the SDK user, so they are response-facing: a newly required payload\n    // field is something the sender now always provides.\n    for (const webhook of spec.webhooks ?? []) responseSeeds.push(...collectWebhookTypeRefs(webhook));\n  }\n\n  const request = reachableModels(requestSeeds, models);\n  const response = reachableModels(responseSeeds, models);\n\n  const index = new Map<string, ModelDirection>();\n  for (const name of models.keys()) {\n    const inRequest = request.has(name);\n    const inResponse = response.has(name);\n    index.set(name, inRequest && inResponse ? 'both' : inRequest ? 'request' : inResponse ? 'response' : 'unknown');\n  }\n  return index;\n}\n\nexport function directionOf(index: DirectionIndex | undefined, modelName: string): ModelDirection {\n  return index?.get(modelName) ?? 'unknown';\n}\n\n/**\n * Every model name reachable from `seeds`, following model fields (and\n * discriminated-union variants) transitively.\n */\nfunction reachableModels(seeds: TypeRef[], models: ReadonlyMap<string, Model>): Set<string> {\n  const found = new Set<string>();\n  const queue = [...seeds];\n\n  while (queue.length > 0) {\n    const ref = queue.pop()!;\n    switch (ref.kind) {\n      case 'model': {\n        if (found.has(ref.name)) break;\n        found.add(ref.name);\n        const model = models.get(ref.name);\n        if (!model) break;\n        // Fields and, for a named union, its variants.\n        queue.push(...collectModelTypeRefs(model));\n        // A dispatcher model reaches its variants by name, not by field type.\n        for (const variant of Object.values(model.discriminator?.mapping ?? {})) {\n          queue.push({ kind: 'model', name: variant });\n        }\n        break;\n      }\n      case 'array':\n        queue.push(ref.items);\n        break;\n      case 'nullable':\n        queue.push(ref.inner);\n        break;\n      case 'map':\n        queue.push(ref.valueType);\n        break;\n      case 'union':\n        queue.push(...ref.variants);\n        break;\n      case 'primitive':\n      case 'enum':\n      case 'literal':\n        break;\n    }\n  }\n\n  return found;\n}\n","import type { Model, TypeRef } from '../ir/types.js';\nimport { assertNever } from '../ir/types.js';\nimport type { Change, FieldChange, VariantChange } from './types.js';\nimport { classifyFieldChange, deprecationDetails, deprecationFlip, extensionsShift } from './classify.js';\nimport type { DirectionIndex, ModelDirection } from './direction.js';\nimport { directionOf } from './direction.js';\n\n/**\n * `directions` (from `buildDirectionIndex`) lets requiredness changes be judged\n * against the side of the wire each model is used on. Omit it and every model is\n * treated as unknown-direction, i.e. the conservative classification.\n */\nexport function diffModels(oldModels: Model[], newModels: Model[], directions?: DirectionIndex): Change[] {\n  const changes: Change[] = [];\n  const oldByName = new Map(oldModels.map((m) => [m.name, m]));\n  const newByName = new Map(newModels.map((m) => [m.name, m]));\n\n  for (const [name] of newByName) {\n    if (!oldByName.has(name)) {\n      changes.push({ kind: 'model-added', name, classification: 'additive' });\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push({ kind: 'model-removed', name, classification: 'breaking' });\n    }\n  }\n\n  for (const [name, newModel] of newByName) {\n    const oldModel = oldByName.get(name);\n    if (!oldModel) continue;\n\n    const fieldChanges = diffFields(oldModel, newModel, directionOf(directions, name));\n    const variantChanges = diffVariants(oldModel, newModel);\n    // A flipped flag alone is a change: nothing the model's callers compile\n    // against moves, but a changelog has to say it.\n    const deprecation = deprecationFlip(oldModel, newModel);\n    // So is a change to the model's own extensions, which are not shape\n    // either; the flag is present only when they differ (`extensionsShift`).\n    const extensions = extensionsShift(oldModel, newModel);\n    if (fieldChanges.length > 0 || variantChanges.length > 0 || deprecation || extensions) {\n      const hasBreaking = [...fieldChanges, ...variantChanges].some((c) => c.classification === 'breaking');\n      changes.push({\n        kind: 'model-modified',\n        name,\n        fieldChanges,\n        ...(variantChanges.length > 0 ? { variantChanges } : {}),\n        deprecatedChanged: deprecation !== undefined,\n        ...deprecation,\n        ...(extensions ? { extensionsChanged: true, ...extensions } : {}),\n        classification: hasBreaking ? 'breaking' : 'additive',\n      });\n    }\n  }\n\n  return changes;\n}\n\n/**\n * Changes to a named union's `variants` and `discriminator`. A variant is\n * matched by type equality (`typeRefsEqual`), not by position, so reordering\n * reports nothing. A model whose `variants` is absent while its discriminator\n * mapping names its variants (an allOf+oneOf dispatcher) is read as a union of\n * the mapping's targets (`dispatchedVariants`), so both forms report alike.\n *\n * An added variant is additive, like a new enum value, from either side of the\n * wire: a caller may now construct it but need not, and a reader may now\n * receive it as it may a new enum value; a required field the union model\n * itself gains is judged by `diffFields` on its own, by direction. A removed\n * variant is breaking, since callers may construct or match it.\n *\n * A mapping entry that comes with an added variant — a new key whose target is\n * a model no variant of the old union names, under any wrapper — or goes with\n * a removed one is part of that variant's change: it is carried as the variant\n * entry's `details` (`mapping added for 'bird'`, `mapping removed for 'dog'`),\n * not reported on its own, so a variant added to a discriminated union is\n * additive whether the spec writes the `mapping` or the parser derives it\n * (`diffMapping`). Every other discriminator change is breaking, since it\n * changes how an existing payload is dispatched: the discriminator added,\n * removed or moved to another property, a key retargeted, a key added for a\n * model the old union already dispatched to (bare or wrapped: `nullable<Cat>`\n * added beside `Cat` brings no new model, so a key for `Cat` added with it is\n * an alias) or for no variant, or a key removed while its model stays. So is a\n * change of composition keyword between two unions (`anyOf` → `oneOf` rejects\n * values that match more than one branch; the reverse loosens what callers may\n * receive). A model that gains or loses `variants` altogether reports each\n * variant added or removed, not a composition change.\n */\nfunction diffVariants(oldModel: Model, newModel: Model): VariantChange[] {\n  const changes: VariantChange[] = [];\n  const oldVariants = dispatchedVariants(oldModel);\n  const newVariants = dispatchedVariants(newModel);\n\n  if (oldModel.compositionKind && newModel.compositionKind && oldModel.compositionKind !== newModel.compositionKind) {\n    changes.push({\n      kind: 'composition-changed',\n      variant: newModel.compositionKind,\n      classification: 'breaking',\n      details: `composition changed from '${oldModel.compositionKind}' to '${newModel.compositionKind}'`,\n    });\n  }\n\n  const added = newVariants.filter((variant) => !oldVariants.some((v) => typeRefsEqual(v, variant)));\n  const removed = oldVariants.filter((variant) => !newVariants.some((v) => typeRefsEqual(v, variant)));\n\n  const oldDisc = oldModel.discriminator;\n  const newDisc = newModel.discriminator;\n  // The mapping is compared entry by entry only while both sides dispatch on\n  // the same property; a discriminator added, removed or moved is one change.\n  const mapping =\n    oldDisc && newDisc && oldDisc.property === newDisc.property\n      ? diffMapping(oldDisc.mapping, newDisc.mapping, oldVariants, newVariants)\n      : { added: new Map<string, string[]>(), removed: new Map<string, string[]>(), changed: [] };\n\n  for (const variant of added) {\n    changes.push({\n      kind: 'variant-added',\n      variant: variantLabel(variant),\n      classification: 'additive',\n      ...mappingDetails('added', mapping.added, variant),\n    });\n  }\n  for (const variant of removed) {\n    changes.push({\n      kind: 'variant-removed',\n      variant: variantLabel(variant),\n      classification: 'breaking',\n      ...mappingDetails('removed', mapping.removed, variant),\n    });\n  }\n\n  if (oldDisc || newDisc) {\n    if (!oldDisc || !newDisc) {\n      changes.push({\n        kind: 'discriminator-changed',\n        variant: (newDisc ?? oldDisc)!.property,\n        classification: 'breaking',\n        details: newDisc ? 'discriminator added' : 'discriminator removed',\n      });\n    } else if (oldDisc.property !== newDisc.property) {\n      changes.push({\n        kind: 'discriminator-changed',\n        variant: newDisc.property,\n        classification: 'breaking',\n        details: `property changed from '${oldDisc.property}' to '${newDisc.property}'`,\n      });\n    } else if (mapping.changed.length > 0) {\n      changes.push({\n        kind: 'discriminator-changed',\n        variant: newDisc.property,\n        classification: 'breaking',\n        details: `mapping changed for ${quoteKeys(mapping.changed)}`,\n      });\n    }\n  }\n\n  return changes;\n}\n\n/**\n * The variants a model dispatches to: its `variants` when it has them, else —\n * for an allOf+oneOf dispatcher, whose `variants` is absent and whose\n * `discriminator.mapping` alone names them — one model ref per distinct\n * mapping target, in mapping order. A model with neither has none.\n */\nfunction dispatchedVariants(model: Model): TypeRef[] {\n  if (model.variants) return model.variants;\n  const names = new Set(Object.values(model.discriminator?.mapping ?? {}));\n  return [...names].map((name) => ({ kind: 'model', name }));\n}\n\n/**\n * The model names a discriminator mapping can dispatch `ref` to: the model\n * itself, or the models under a nullable or multi-type variant's wrapper (the\n * parser keeps the wrapper around the model it extracts for such a variant).\n * A primitive, enum, literal, array or map variant is never a mapping target.\n */\nfunction variantModelNames(ref: TypeRef): string[] {\n  switch (ref.kind) {\n    case 'model':\n      return [ref.name];\n    case 'nullable':\n      return variantModelNames(ref.inner);\n    case 'union':\n      return ref.variants.flatMap(variantModelNames);\n    case 'primitive':\n    case 'enum':\n    case 'literal':\n    case 'array':\n    case 'map':\n      return [];\n  }\n  return assertNever(ref);\n}\n\n/** How the two mappings of one discriminator property differ, each key read once. */\ninterface MappingDiff {\n  /** Keys the new mapping adds for a model no old variant names, by that model's name. */\n  added: Map<string, string[]>;\n  /** Keys the old mapping had for a model no new variant names, by that model's name. */\n  removed: Map<string, string[]>;\n  /** Keys added, removed or retargeted on their own, sorted: each changes how an existing payload is dispatched. */\n  changed: string[];\n}\n\n/**\n * Compare two mappings key by key and sort each differing key into the\n * variant addition or removal it belongs to, or into `changed`. Whether a\n * model is new is decided on its name after every wrapper is flattened on both\n * sides (`variantModelNames`), not on the variant's type: `nullable<Cat>`\n * added beside a kept `Cat` is a new variant but no new model, so a key for\n * `Cat` added with it is an alias and `changed`. A key only the new mapping has\n * belongs to an addition when its target names a model no old variant names;\n * a key only the old mapping has belongs to a removal when its target names a\n * model no new variant names; a key on both sides with different targets, or\n * on one side for a model the other side still dispatches to (or for no\n * variant), is `changed`. Keys are visited sorted, so the lists are\n * deterministic whatever the document order.\n */\nfunction diffMapping(\n  oldMapping: Record<string, string>,\n  newMapping: Record<string, string>,\n  oldVariants: readonly TypeRef[],\n  newVariants: readonly TypeRef[],\n): MappingDiff {\n  const oldNames = new Set(oldVariants.flatMap(variantModelNames));\n  const newNames = new Set(newVariants.flatMap(variantModelNames));\n  const addedNames = new Set([...newNames].filter((name) => !oldNames.has(name)));\n  const removedNames = new Set([...oldNames].filter((name) => !newNames.has(name)));\n  const diff: MappingDiff = { added: new Map(), removed: new Map(), changed: [] };\n  const push = (into: Map<string, string[]>, name: string, key: string): void => {\n    into.set(name, [...(into.get(name) ?? []), key]);\n  };\n  // Own keys only, so a value spelled like an inherited property\n  // (`constructor`) on one side is compared against nothing, not against\n  // `Object.prototype`'s.\n  const own = (mapping: Record<string, string>, key: string): string | undefined =>\n    Object.hasOwn(mapping, key) ? mapping[key] : undefined;\n  const keys = [...new Set([...Object.keys(oldMapping), ...Object.keys(newMapping)])].sort();\n  for (const key of keys) {\n    const oldTarget = own(oldMapping, key);\n    const newTarget = own(newMapping, key);\n    if (oldTarget === newTarget) continue;\n    if (oldTarget === undefined && newTarget !== undefined && addedNames.has(newTarget)) {\n      push(diff.added, newTarget, key);\n    } else if (newTarget === undefined && oldTarget !== undefined && removedNames.has(oldTarget)) {\n      push(diff.removed, oldTarget, key);\n    } else {\n      diff.changed.push(key);\n    }\n  }\n  return diff;\n}\n\n/**\n * The `details` a `variant-added` / `variant-removed` entry carries when\n * mapping keys came or went with the variant (`mapping added for 'bird'`,\n * `mapping removed for 'dog'`); nothing when none did, so an undiscriminated\n * union's entries carry no `details` key. The keys of every model the variant\n * names are listed once each, sorted, so a multi-type variant's text does not\n * depend on the order of its members.\n */\nfunction mappingDetails(\n  change: 'added' | 'removed',\n  keysByName: ReadonlyMap<string, string[]>,\n  variant: TypeRef,\n): { details: string } | Record<string, never> {\n  const keys = [...new Set(variantModelNames(variant).flatMap((name) => keysByName.get(name) ?? []))].sort();\n  return keys.length > 0 ? { details: `mapping ${change} for ${quoteKeys(keys)}` } : {};\n}\n\nfunction quoteKeys(keys: readonly string[]): string {\n  return keys.map((k) => `'${k}'`).join(', ');\n}\n\n/** A short, human-readable label for a union variant in a change report. */\nfunction variantLabel(ref: TypeRef): string {\n  switch (ref.kind) {\n    case 'model':\n    case 'enum':\n      return ref.name;\n    case 'primitive':\n      return ref.format ? `${ref.type}:${ref.format}` : ref.type;\n    case 'literal':\n      return `literal:${String(ref.value)}`;\n    case 'nullable':\n      return `nullable<${variantLabel(ref.inner)}>`;\n    case 'array':\n      return `array<${variantLabel(ref.items)}>`;\n    case 'map':\n      return `map<${variantLabel(ref.valueType)}>`;\n    case 'union':\n      return `union<${ref.variants.map(variantLabel).join('|')}>`;\n  }\n  return assertNever(ref);\n}\n\nfunction diffFields(oldModel: Model, newModel: Model, direction: ModelDirection = 'unknown'): FieldChange[] {\n  const changes: FieldChange[] = [];\n  const oldByName = new Map(oldModel.fields.map((f) => [f.name, f]));\n  const newByName = new Map(newModel.fields.map((f) => [f.name, f]));\n\n  for (const [name, field] of newByName) {\n    if (!oldByName.has(name)) {\n      // Only `field-added` consults direction today. `field-required-changed`\n      // deliberately stays direction-blind: downstream changelog tooling reads\n      // its `breaking` classification as \"made required\", so downgrading it\n      // would invert the wording rather than just soften the severity.\n      changes.push(classifyFieldChange('field-added', name, field.required, direction));\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push(classifyFieldChange('field-removed', name));\n    }\n  }\n\n  for (const [name, newField] of newByName) {\n    const oldField = oldByName.get(name);\n    if (!oldField) continue;\n\n    if (!typeRefsEqual(oldField.type, newField.type)) {\n      if (primitivesDifferOnlyByFormat(oldField.type, newField.type)) {\n        changes.push({\n          ...classifyFieldChange('field-format-changed', name),\n          details: formatChangeDetails(oldField.type, newField.type),\n        });\n      } else {\n        changes.push({\n          kind: 'field-type-changed',\n          fieldName: name,\n          classification: 'breaking',\n          details: `type changed`,\n        });\n      }\n    }\n\n    if (oldField.required !== newField.required) {\n      changes.push(classifyFieldChange('field-required-changed', name, newField.required));\n    }\n\n    if (!!oldField.readOnly !== !!newField.readOnly || !!oldField.writeOnly !== !!newField.writeOnly) {\n      changes.push(classifyFieldChange('field-access-changed', name));\n    }\n\n    const deprecation = deprecationFlip(oldField, newField);\n    if (deprecation) {\n      changes.push({\n        ...classifyFieldChange('field-deprecated-changed', name),\n        ...deprecation,\n        details: deprecationDetails(deprecation.newDeprecated),\n      });\n    }\n\n    // The field's own extensions are not shape either; reported beside, not\n    // instead of, whatever else changed about the field.\n    const extensions = extensionsShift(oldField, newField);\n    if (extensions) {\n      changes.push({ ...classifyFieldChange('field-extensions-changed', name), ...extensions });\n    }\n  }\n\n  return changes;\n}\n\n/**\n * True when both refs are primitives with the same base `type` but different\n * `format`. Used to downgrade format-only diffs from breaking type changes to\n * additive `field-format-changed` / `param-format-changed` events: the wire\n * base type is unchanged, so the diff is a hint to language emitters rather\n * than a source-level break.\n */\nexport function primitivesDifferOnlyByFormat(a: TypeRef, b: TypeRef): boolean {\n  if (a.kind !== 'primitive' || b.kind !== 'primitive') return false;\n  if (a.type !== b.type) return false;\n  return (a.format ?? '') !== (b.format ?? '');\n}\n\nexport function formatChangeDetails(a: TypeRef, b: TypeRef): string {\n  const oldFmt = a.kind === 'primitive' ? a.format : undefined;\n  const newFmt = b.kind === 'primitive' ? b.format : undefined;\n  return `format ${oldFmt ?? '<unset>'} → ${newFmt ?? '<unset>'}`;\n}\n\nexport function typeRefsEqual(a: TypeRef, b: TypeRef): boolean {\n  if (a.kind !== b.kind) return false;\n\n  switch (a.kind) {\n    case 'primitive':\n      return b.kind === 'primitive' && a.type === b.type && (a.format ?? '') === ((b as typeof a).format ?? '');\n    case 'array':\n      return b.kind === 'array' && typeRefsEqual(a.items, b.items);\n    case 'model':\n      return b.kind === 'model' && a.name === b.name;\n    case 'enum':\n      return b.kind === 'enum' && a.name === b.name;\n    case 'literal':\n      return b.kind === 'literal' && a.value === b.value;\n    case 'nullable':\n      return b.kind === 'nullable' && typeRefsEqual(a.inner, b.inner);\n    case 'union': {\n      if (b.kind !== 'union') return false;\n      if (a.variants.length !== b.variants.length) return false;\n      if (!a.variants.every((v, i) => typeRefsEqual(v, b.variants[i]))) return false;\n      // Compare discriminator\n      if (!a.discriminator && !b.discriminator) return true;\n      if (!a.discriminator || !b.discriminator) return false;\n      if (a.discriminator.property !== b.discriminator.property) return false;\n      const aKeys = Object.keys(a.discriminator.mapping).sort();\n      const bKeys = Object.keys(b.discriminator.mapping).sort();\n      if (aKeys.length !== bKeys.length) return false;\n      return aKeys.every((k, i) => k === bKeys[i] && a.discriminator!.mapping[k] === b.discriminator!.mapping[k]);\n    }\n    case 'map':\n      return b.kind === 'map' && typeRefsEqual(a.valueType, b.valueType);\n  }\n  return assertNever(a);\n}\n","import type { SecurityRequirementSet } from '../ir/types.js';\n\n/**\n * The two documents' `security`, so a node that declares none of its own can\n * be compared on what it actually inherits (`node.security ?? document\n * security`). `diffSpecs` supplies it; a direct caller may leave it out, in\n * which case a node that inherits is compared as requiring no authentication.\n */\nexport interface DocumentSecurity {\n  old: SecurityRequirementSet[] | undefined;\n  new: SecurityRequirementSet[] | undefined;\n}\n\n/**\n * Which side of the wire reads a security change. A `caller` (an operation's\n * client) built for the old requirements presents one of the old alternatives\n * and must still satisfy the new; a `receiver` (a webhook handler) built for\n * the old requirements checks for one of the old alternatives, and whatever\n * the sender now presents — one of the new alternatives — must still carry it.\n */\nexport type SecuritySide = 'caller' | 'receiver';\n\n/** The two sides of a security change, carried on the change that reports it. */\nexport interface SecurityShift {\n  /** What a request had to satisfy before: the node's own list, else the document's, `[]` when neither declares any. */\n  oldSecurity: SecurityRequirementSet[];\n  /** What a request has to satisfy now, resolved the same way. */\n  newSecurity: SecurityRequirementSet[];\n}\n\n/** One alternative, folded so it compares as a set: scheme name → the scopes it needs. */\ntype Alternative = Map<string, Set<string>>;\n\n/**\n * The alternatives a requirement list offers, each folded for set comparison.\n * `[]` (`security: []`) and a list left `undefined` everywhere both mean no\n * authentication, which is one alternative that needs nothing — the same\n * thing a document spells as `[{}]` — so the three compare equal.\n */\nfunction alternativesOf(sets: SecurityRequirementSet[]): Alternative[] {\n  const alternatives = sets.length === 0 ? [[]] : sets;\n  return alternatives.map((set) => {\n    const folded: Alternative = new Map();\n    for (const requirement of set) {\n      const scopes = folded.get(requirement.schemeName) ?? new Set<string>();\n      for (const scope of requirement.scopes) scopes.add(scope);\n      folded.set(requirement.schemeName, scopes);\n    }\n    return folded;\n  });\n}\n\n/** Whether `presented` carries everything `required` asks for: every scheme, with every scope. */\nfunction covers(presented: Alternative, required: Alternative): boolean {\n  for (const [schemeName, scopes] of required) {\n    const carried = presented.get(schemeName);\n    if (!carried) return false;\n    for (const scope of scopes) if (!carried.has(scope)) return false;\n  }\n  return true;\n}\n\n/**\n * Whether two requirement lists demand the same thing: the same alternatives\n * as a set, each the same schemes with the same scopes as sets. Order,\n * repeated alternatives and repeated scopes do not count.\n */\nexport function securityEqual(a: SecurityRequirementSet[], b: SecurityRequirementSet[]): boolean {\n  const left = alternativesOf(a);\n  const right = alternativesOf(b);\n  const same = (x: Alternative, y: Alternative): boolean => covers(x, y) && covers(y, x);\n  return left.every((x) => right.some((y) => same(x, y))) && right.every((y) => left.some((x) => same(x, y)));\n}\n\n/**\n * Whether a request built for `presented` still satisfies `required`: every\n * alternative of `presented` carries everything some alternative of\n * `required` asks for. A requirement that offers an anonymous alternative\n * (`[{}]`, or no authentication at all) is satisfied by anything.\n */\nexport function securitySatisfied(required: SecurityRequirementSet[], presented: SecurityRequirementSet[]): boolean {\n  const alternatives = alternativesOf(required);\n  return alternativesOf(presented).every((carried) => alternatives.some((asked) => covers(carried, asked)));\n}\n\n/**\n * How a change from `oldSecurity` to `newSecurity` lands on `side`. Breaking\n * when a request built for the old list no longer passes: for a caller, some\n * old alternative satisfies no new one (a scheme or scope a request now has\n * to carry, an alternative it could use that is gone, an anonymous\n * alternative withdrawn); for a receiver, some new alternative carries no old\n * one (a scheme the sender stops presenting, an alternative it may now use\n * that the handler never checked for). Additive otherwise: a new alternative\n * a caller may use, a scope or scheme it no longer needs, a credential the\n * sender starts carrying beside what the handler already checks.\n */\nexport function classifySecurityChange(\n  oldSecurity: SecurityRequirementSet[],\n  newSecurity: SecurityRequirementSet[],\n  side: SecuritySide,\n): 'additive' | 'breaking' {\n  const stillPasses =\n    side === 'caller' ? securitySatisfied(newSecurity, oldSecurity) : securitySatisfied(oldSecurity, newSecurity);\n  return stillPasses ? 'additive' : 'breaking';\n}\n\n/**\n * `{ oldSecurity, newSecurity }` when what a node's requests must carry\n * differs between the two documents, `undefined` when it does not. Each side\n * is the node's own `security`, else that document's (`document`), else none.\n * Absent on both sides is \"inherits\" twice: a moved document default is the\n * document-level `security-changed` entry's to report, so it is not a change\n * to the node. Otherwise the two effective lists are compared, so a document\n * that moves to what the node already declared (and the node's override\n * vanishing with it) is no change to the node.\n */\nexport function securityShift(\n  oldNode: { security?: SecurityRequirementSet[] },\n  newNode: { security?: SecurityRequirementSet[] },\n  document?: DocumentSecurity,\n): SecurityShift | undefined {\n  if (oldNode.security === undefined && newNode.security === undefined) return undefined;\n  const oldSecurity = oldNode.security ?? document?.old ?? [];\n  const newSecurity = newNode.security ?? document?.new ?? [];\n  return securityEqual(oldSecurity, newSecurity) ? undefined : { oldSecurity, newSecurity };\n}\n","import type { ApiSpec, ServerEntry, ServerVariable } from '../ir/types.js';\nimport {\n  baseUrlBeyondDefault,\n  isDefaultServerList,\n  normalizeServerUrl,\n  resolveServerUrl,\n  serverUrlPlaceholders,\n  serversOrDefault,\n} from '../ir/server-url.js';\nimport type { ServerChange, ServerVariableChange } from './types.js';\n\n/**\n * Compare the two documents' `baseUrl` and `servers`.\n *\n * Every URL — `baseUrl` and each `url` template — is compared through\n * `normalizeServerUrl`, so two spellings RFC 3986 calls equivalent are one\n * URL: a scheme or host that only changed case, a default port written or\n * dropped, a `/` added after a bare authority, a percent-encoded octet whose\n * hex digits changed case. The path, query and variable values are\n * case-sensitive. Every URL a change carries is reported as written in the\n * document that declares it.\n *\n * `base-url-changed` is reported once whenever the resolved default host\n * differs, on top of whichever server change moved it, so a consumer that only\n * cares where the client's default host points finds it without reconstructing\n * `servers[0]`. It is the only change a reordered list produces.\n *\n * Servers are matched on their normalised `url` template, independent of\n * position: a changed template is a `server-removed` plus a `server-added`.\n * A template the document declares more than once is matched as a multiset.\n * Its old and new entries pair up by the strongest signal available, each pass\n * taking the first unmatched candidate in declaration order: identical\n * variables first, so a reordered list, or one whose duplicates are unchanged,\n * reports nothing; then the same variable defaults (the entry kept its\n * identity and changed its enums); then the same normalised resolved URL (it\n * differs only in a variable the template does not use); then position. The\n * surplus on either side is a `server-added` or a `server-removed`. Within a\n * matched pair, variables are matched by name and every difference is\n * collected on one `server-modified` carrying the new document's spelling of\n * the template; a change to a variable the template never references is\n * additive whatever its kind, since no resolved URL can move, and so is a\n * changed default that moves no resolved URL in its RFC 3986 form (see\n * `diffServerVariables`). Descriptions are not compared, as nowhere else in\n * the differ.\n *\n * OpenAPI's default server is one thing however a document spells it (#291):\n * no `servers`, `servers: []`, and `servers: [{ url: '/' }]` (description and\n * variables aside: `/` references no variable, so one declared on it changes\n * nothing — #292) are all matched as `[{ url: '/' }]`\n * (`serversOrDefault`), so nothing is reported between two such documents\n * and `/` gaining a named host beside it is one `server-added`, losing that\n * host one `server-removed`. The `/` a document is only implied to have is\n * never a `server-added` or a `server-removed` itself: a document that moves\n * from any spelling of the default to a named host gains it as additive with\n * no `server-removed` for `/`, and the reverse has no `server-added` for\n * `/`. A `/` listed beside another server is one a caller can pick, so it is\n * added and removed like any other, and listed first it is the address a\n * caller gets without naming a host: a host taking the front from it, by a\n * reorder or because it was removed, is a breaking `base-url-changed`, which\n * is additive only from a document whose list means the default (#405). The\n * default address is compared through `baseUrlBeyondDefault`, which reads\n * `''` and `/` as one, so a document whose first server merely resolves to\n * `/` has not moved (a host taking the front from it is breaking all the\n * same), while a `baseUrl` naming a host with no `servers` beside it — an IR\n * built by hand, which the parser never produces — is compared as written.\n * `oldBaseUrl` and `newBaseUrl` still carry `ApiSpec.baseUrl` as the parser\n * set it, `/` included.\n *\n * `diffOperations` compares an operation's two effective server lists\n * through this same function, each read as a document whose `baseUrl` is\n * its first entry resolved, and carries the result as `serverChanges` on the\n * `operation-modified` change, so an edit is classified the same whether it\n * sits on the document, a Path Item or an Operation (#299).\n */\nexport function diffServers(\n  oldSpec: Pick<ApiSpec, 'baseUrl' | 'servers'>,\n  newSpec: Pick<ApiSpec, 'baseUrl' | 'servers'>,\n): ServerChange[] {\n  const changes: ServerChange[] = [];\n\n  // A document that declares nothing beyond the default is served from\n  // OpenAPI's single `/`, so that is what it is matched as.\n  const oldServers = serversOrDefault(oldSpec.servers);\n  const newServers = serversOrDefault(newSpec.servers);\n  const oldImplied = isDefaultServerList(oldSpec.servers);\n  const newImplied = isDefaultServerList(newSpec.servers);\n  // `''` and `/` are one address — the default — on either side, so only a\n  // move to or from somewhere else is a change. Any other `baseUrl` is\n  // compared as written, even with no `servers` beside it.\n  const oldBaseUrl = baseUrlBeyondDefault(oldSpec.baseUrl);\n  const newBaseUrl = baseUrlBeyondDefault(newSpec.baseUrl);\n\n  if (normalizeServerUrl(oldBaseUrl) !== normalizeServerUrl(newBaseUrl)) {\n    changes.push({\n      kind: 'base-url-changed',\n      oldBaseUrl: oldSpec.baseUrl,\n      newBaseUrl: newSpec.baseUrl,\n      // A default host appearing where the old list meant only the default\n      // leaves every existing caller — who had to name a host — working. One\n      // moving or disappearing does not, and neither does a host taking the\n      // front from a `/` the old list named beside another server: that `/`\n      // was the address a caller got without naming one (#405).\n      classification: oldBaseUrl === '' && oldImplied ? 'additive' : 'breaking',\n    });\n  }\n\n  const oldByUrl = groupByUrl(oldServers);\n  const newByUrl = groupByUrl(newServers);\n\n  const pairings = new Map<string, ServerPairing>();\n  for (const url of new Set([...oldByUrl.keys(), ...newByUrl.keys()])) {\n    pairings.set(url, pairServers(oldByUrl.get(url) ?? [], newByUrl.get(url) ?? []));\n  }\n\n  // The `/` a document is only implied to have (its list means the default,\n  // so it was matched as `[{ url: '/' }]` above) is not a server a caller\n  // gained or lost: left unmatched, it is not reported. A side that lists\n  // anything beyond the default has no implied entry, so every surplus there\n  // is reported, a `/` beside a named host included. Each surplus entry is\n  // reported with its own spelling.\n  if (!newImplied) {\n    for (const url of newByUrl.keys()) {\n      for (const server of pairings.get(url)!.surplusNew) {\n        changes.push({ kind: 'server-added', url: server.url, classification: 'additive' });\n      }\n    }\n  }\n\n  if (!oldImplied) {\n    for (const url of oldByUrl.keys()) {\n      for (const server of pairings.get(url)!.surplusOld) {\n        changes.push({ kind: 'server-removed', url: server.url, classification: 'breaking' });\n      }\n    }\n  }\n\n  for (const url of newByUrl.keys()) {\n    for (const [oldServer, newServer] of pairings.get(url)!.pairs) {\n      const variableChanges = diffServerVariables(oldServer, newServer);\n      if (variableChanges.length > 0) {\n        const hasBreaking = variableChanges.some((vc) => vc.classification === 'breaking');\n        changes.push({\n          kind: 'server-modified',\n          url: newServer.url,\n          variableChanges,\n          classification: hasBreaking ? 'breaking' : 'additive',\n        });\n      }\n    }\n  }\n\n  return changes;\n}\n\n/**\n * Every entry with each `url` template, keyed by the template's normalised\n * form (`normalizeServerUrl`) in declaration order of the first one. Each\n * entry keeps its own spelling for the report.\n */\nfunction groupByUrl(servers: readonly ServerEntry[]): Map<string, ServerEntry[]> {\n  const groups = new Map<string, ServerEntry[]>();\n  for (const server of servers) {\n    const key = normalizeServerUrl(server.url);\n    const group = groups.get(key);\n    if (group) group.push(server);\n    else groups.set(key, [server]);\n  }\n  return groups;\n}\n\ninterface ServerPairing {\n  /** Old and new entries that differ, paired in declaration order. */\n  pairs: Array<[ServerEntry, ServerEntry]>;\n  /** Old entries with no counterpart, in declaration order: removed. */\n  surplusOld: ServerEntry[];\n  /** New entries with no counterpart, in declaration order: added. */\n  surplusNew: ServerEntry[];\n}\n\n/**\n * Pair the old and new entries of one template, strongest signal first. Each\n * pass walks the old entries still unmatched and gives each the first new\n * entry still unmatched that passes; what neither pass claims pairs by\n * position. Equal defaults imply an equal resolved URL, so that stricter pass\n * has to run first or it would never select anything.\n */\nfunction pairServers(olds: ServerEntry[], news: ServerEntry[]): ServerPairing {\n  let unmatchedOld = [...olds];\n  const unmatchedNew = [...news];\n  const pairs: Array<[ServerEntry, ServerEntry]> = [];\n\n  for (const same of [identicalVariables, sameDefaults, sameResolvedUrl]) {\n    const stillUnmatched: ServerEntry[] = [];\n    for (const oldServer of unmatchedOld) {\n      const twin = unmatchedNew.findIndex((newServer) => same(oldServer, newServer));\n      if (twin === -1) stillUnmatched.push(oldServer);\n      else pairs.push([oldServer, unmatchedNew.splice(twin, 1)[0]]);\n    }\n    unmatchedOld = stillUnmatched;\n  }\n\n  const paired = Math.min(unmatchedOld.length, unmatchedNew.length);\n  for (let i = 0; i < paired; i++) pairs.push([unmatchedOld[i], unmatchedNew[i]]);\n\n  // Report in the new document's order, like every other change.\n  pairs.sort((a, b) => news.indexOf(a[1]) - news.indexOf(b[1]));\n\n  return { pairs, surplusOld: unmatchedOld.slice(paired), surplusNew: unmatchedNew.slice(paired) };\n}\n\nfunction identicalVariables(a: ServerEntry, b: ServerEntry): boolean {\n  return diffServerVariables(a, b).length === 0;\n}\n\n/** The same variable names with the same defaults; enums and descriptions aside. */\nfunction sameDefaults(a: ServerEntry, b: ServerEntry): boolean {\n  const aVars = Object.entries(a.variables ?? {});\n  const bVars = b.variables ?? {};\n  return (\n    aVars.length === Object.keys(bVars).length &&\n    aVars.every(([name, variable]) => Object.hasOwn(bVars, name) && bVars[name].default === variable.default)\n  );\n}\n\n/** The same resolved URL up to `normalizeServerUrl`, like every URL comparison in this file. */\nfunction sameResolvedUrl(a: ServerEntry, b: ServerEntry): boolean {\n  return normalizeServerUrl(resolveServerUrl(a).url) === normalizeServerUrl(resolveServerUrl(b).url);\n}\n\n/**\n * Every difference between the variables of two entries with the same `url`\n * template, matched by name.\n *\n * Whether a difference is breaking depends on whether the template references\n * the variable. A `{name}` in the template is filled from that variable's\n * `default`, or from a value the caller picks, so removing the variable,\n * changing its default or narrowing its values moves a resolved URL some\n * caller was built on: breaking. A changed default moves nothing, though,\n * when the template with only that variable filled in reads the same\n * through `normalizeServerUrl` from either default, as when only the host's\n * case changed (#406): that change is additive, with `details` saying why,\n * and is still reported, since defaults are compared as written. The\n * template's other placeholders are kept rather than filled from their\n * defaults, since a caller may pick any value for them and\n * `normalizeServerUrl` folds only what no such value can change. A declared\n * variable the template never references (`serverUrlPlaceholders` does not\n * list it; the parser keeps it as written) cannot reach any resolved URL, so\n * the same differences take nothing away from any caller and are additive,\n * with `details` saying why. The template is the same on both sides, since\n * entries are matched on it, so one reading of it serves the pair. The kinds\n * that are additive for any variable (a variable added, an enum lifted, an\n * enum value added) are not affected.\n */\nfunction diffServerVariables(oldServer: ServerEntry, newServer: ServerEntry): ServerVariableChange[] {\n  const changes: ServerVariableChange[] = [];\n  // Own enumerable keys only: the parser defines each variable as an own data\n  // property, so one named `constructor` or `__proto__` is compared like any\n  // other and nothing is read from Object.prototype.\n  const oldByName = new Map(Object.entries(oldServer.variables ?? {}));\n  const newByName = new Map(Object.entries(newServer.variables ?? {}));\n  const referenced = new Set(serverUrlPlaceholders(oldServer.url));\n\n  for (const [name] of newByName) {\n    if (!oldByName.has(name)) {\n      // A new knob. If its placeholder was already in the template, the\n      // resolved URL moves too, which `base-url-changed` reports for servers[0].\n      changes.push({ kind: 'variable-added', variableName: name, classification: 'additive' });\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push(breakingIfReferenced({ kind: 'variable-removed', variableName: name }, referenced));\n    }\n  }\n\n  for (const [name, newVar] of newByName) {\n    const oldVar = oldByName.get(name);\n    if (!oldVar) continue;\n\n    if (oldVar.default !== newVar.default) {\n      const change: Omit<ServerVariableChange, 'classification'> = {\n        kind: 'variable-default-changed',\n        variableName: name,\n        oldDefault: oldVar.default,\n        newDefault: newVar.default,\n        details: `default changed from '${oldVar.default}' to '${newVar.default}'`,\n      };\n      // The default is what a caller gets without choosing, so when the\n      // template references the variable this moves the server's resolved\n      // URL whether or not it is servers[0], unless the template with only\n      // this variable filled in is one URL in its RFC 3986 form from either\n      // default, as when only the host's case changes (#406). The other\n      // placeholders stay, since a caller may pick any value for them: beside\n      // `{scheme}`, `{port}` going from `443` to `''` moves an `http` caller\n      // from port 443 to 80.\n      const sameUrl =\n        referenced.has(name) &&\n        sameResolvedUrl(\n          { url: oldServer.url, variables: { [name]: oldVar } },\n          { url: oldServer.url, variables: { [name]: newVar } },\n        );\n      changes.push(\n        sameUrl\n          ? {\n              ...change,\n              classification: 'additive',\n              details: `${change.details}; either default resolves to the same URL in its RFC 3986 form`,\n            }\n          : breakingIfReferenced(change, referenced),\n      );\n    }\n\n    changes.push(...diffVariableEnum(name, oldVar, newVar, referenced));\n  }\n\n  return changes;\n}\n\n/**\n * Classify a variable difference that moves a resolved URL when the template\n * references the variable: breaking then, additive otherwise — with\n * `details` extended to say why, since the kind alone reads as breaking.\n */\nfunction breakingIfReferenced(\n  change: Omit<ServerVariableChange, 'classification'>,\n  referenced: ReadonlySet<string>,\n): ServerVariableChange {\n  if (referenced.has(change.variableName)) return { ...change, classification: 'breaking' };\n  const reason = `{${change.variableName}} is not in the URL template, so no resolved URL moves`;\n  return { ...change, classification: 'additive', details: change.details ? `${change.details}; ${reason}` : reason };\n}\n\nfunction diffVariableEnum(\n  name: string,\n  oldVar: ServerVariable,\n  newVar: ServerVariable,\n  referenced: ReadonlySet<string>,\n): ServerVariableChange[] {\n  const oldEnum = oldVar.enum;\n  const newEnum = newVar.enum;\n  if (!oldEnum && !newEnum) return [];\n\n  if (!oldEnum) {\n    // Any value was accepted; now only the listed ones are.\n    return [\n      breakingIfReferenced(\n        { kind: 'variable-enum-added', variableName: name, details: `values restricted to ${newEnum!.join(', ')}` },\n        referenced,\n      ),\n    ];\n  }\n\n  if (!newEnum) {\n    // The restriction is lifted: every value a caller picked before still works.\n    return [\n      {\n        kind: 'variable-enum-removed',\n        variableName: name,\n        classification: 'additive',\n        details: `any value accepted; was ${oldEnum.join(', ')}`,\n      },\n    ];\n  }\n\n  const changes: ServerVariableChange[] = [];\n\n  for (const value of newEnum) {\n    if (!oldEnum.includes(value)) {\n      changes.push({ kind: 'variable-enum-value-added', variableName: name, value, classification: 'additive' });\n    }\n  }\n\n  for (const value of oldEnum) {\n    if (!newEnum.includes(value)) {\n      changes.push(\n        breakingIfReferenced({ kind: 'variable-enum-value-removed', variableName: name, value }, referenced),\n      );\n    }\n  }\n\n  return changes;\n}\n","import type { ApiSpec, Enum, Model, TypeRef } from '../ir/types.js';\nimport { typeRefsEqual } from './models.js';\n\n/** The named types of one document, so a body's model or enum ref can be read through to its shape. */\nexport interface DocumentTypes {\n  models: ReadonlyMap<string, Model>;\n  enums: ReadonlyMap<string, Enum>;\n}\n\n/**\n * The two documents' named types. `diffSpecs` supplies them so paired bodies\n * compare by shape (`sameShape`); a direct caller may leave them out, in\n * which case bodies compare by name alone, as `typeRefsEqual` does.\n */\nexport interface DocumentShapes {\n  old: DocumentTypes;\n  new: DocumentTypes;\n}\n\nexport function documentTypes(spec: Pick<ApiSpec, 'models' | 'enums'>): DocumentTypes {\n  return {\n    models: new Map(spec.models.map((model) => [model.name, model])),\n    enums: new Map(spec.enums.map((entry) => [entry.name, entry])),\n  };\n}\n\n/** Field properties that only document a field — its extensions included; two shapes that differ in these alone are one shape. */\nconst FIELD_DOC_KEYS: ReadonlySet<string> = new Set([\n  'name',\n  'type',\n  'description',\n  'externalDocs',\n  'example',\n  'examples',\n  'extensions',\n]);\n/** Model properties outside its shape: the name, its documentation (extensions included), and what is compared on its own (fields, variants, discriminator). */\nconst MODEL_IDENTITY_KEYS: ReadonlySet<string> = new Set([\n  'name',\n  'description',\n  'externalDocs',\n  'extensions',\n  'fields',\n  'variants',\n  'discriminator',\n]);\n/** Enum value properties that only document the value. */\nconst ENUM_VALUE_DOC_KEYS: ReadonlySet<string> = new Set(['description']);\n\n/**\n * Whether two body types are one shape, whatever names they carry. A type\n * equal by name (`typeRefsEqual`) is one shape; otherwise a model ref is read\n * through to its model in its own document and compared field by field —\n * the same field names, each with the same requiredness, access flags,\n * deprecation, default and limits, and a type that is itself one shape, so\n * nested models and enums are read through too — plus the model's own\n * limits, type parameters, deprecation, variants (pairwise, in order) and\n * discriminator (property and mapped shapes); an enum ref is read through to\n * its values (name, value, deprecation). Documentation (descriptions, links,\n * examples) does not count. Without `shapes`, or for a name either document\n * lacks, the two refs are different shapes. A pair of models met again while\n * comparing their own fields (a self-referential shape) is taken as equal, so\n * the comparison terminates.\n *\n * This is what lets a body the parser names after its media type keep\n * comparing equal across a rename: a parameter edit on a key declared beside\n * another spelling of its essence (`application/yaml; version=1` →\n * `; version=3`) renames the model minted for it, and that rename is the\n * models diff's to report (`model-removed` + `model-added`), not a retype.\n */\nexport function sameShape(a: TypeRef, b: TypeRef, shapes?: DocumentShapes): boolean {\n  return sameShapeWithin(a, b, shapes, new Set());\n}\n\nfunction sameShapeWithin(a: TypeRef, b: TypeRef, shapes: DocumentShapes | undefined, seen: Set<string>): boolean {\n  if (typeRefsEqual(a, b)) return true;\n  if (!shapes || a.kind !== b.kind) return false;\n  switch (a.kind) {\n    case 'model': {\n      if (b.kind !== 'model') return false;\n      const oldModel = shapes.old.models.get(a.name);\n      const newModel = shapes.new.models.get(b.name);\n      if (!oldModel || !newModel) return false;\n      const pair = `model:${a.name}\\u0000${b.name}`;\n      if (seen.has(pair)) return true;\n      seen.add(pair);\n      return sameModelShape(oldModel, newModel, shapes, seen);\n    }\n    case 'enum': {\n      if (b.kind !== 'enum') return false;\n      const oldEnum = shapes.old.enums.get(a.name);\n      const newEnum = shapes.new.enums.get(b.name);\n      if (!oldEnum || !newEnum) return false;\n      return sameEnumShape(oldEnum, newEnum);\n    }\n    case 'array':\n      return b.kind === 'array' && sameShapeWithin(a.items, b.items, shapes, seen);\n    case 'map':\n      return b.kind === 'map' && sameShapeWithin(a.valueType, b.valueType, shapes, seen);\n    case 'nullable':\n      return b.kind === 'nullable' && sameShapeWithin(a.inner, b.inner, shapes, seen);\n    case 'union':\n      return (\n        b.kind === 'union' &&\n        sameVariants(a.variants, b.variants, shapes, seen) &&\n        sameDiscriminator(a.discriminator, b.discriminator, shapes, seen)\n      );\n    default:\n      // Primitives and literals are equal exactly when `typeRefsEqual` says so.\n      return false;\n  }\n}\n\nfunction sameModelShape(oldModel: Model, newModel: Model, shapes: DocumentShapes, seen: Set<string>): boolean {\n  const oldFields = new Map(oldModel.fields.map((field) => [field.name, field]));\n  const newFields = new Map(newModel.fields.map((field) => [field.name, field]));\n  if (oldFields.size !== newFields.size) return false;\n  for (const [name, oldField] of oldFields) {\n    const newField = newFields.get(name);\n    if (!newField) return false;\n    if (stableStringify(omitKeys(oldField, FIELD_DOC_KEYS)) !== stableStringify(omitKeys(newField, FIELD_DOC_KEYS))) {\n      return false;\n    }\n    if (!sameShapeWithin(oldField.type, newField.type, shapes, seen)) return false;\n  }\n  if (\n    stableStringify(omitKeys(oldModel, MODEL_IDENTITY_KEYS)) !==\n    stableStringify(omitKeys(newModel, MODEL_IDENTITY_KEYS))\n  ) {\n    return false;\n  }\n  if (!!oldModel.variants !== !!newModel.variants) return false;\n  if (oldModel.variants && newModel.variants && !sameVariants(oldModel.variants, newModel.variants, shapes, seen)) {\n    return false;\n  }\n  return sameDiscriminator(oldModel.discriminator, newModel.discriminator, shapes, seen);\n}\n\nfunction sameVariants(a: TypeRef[], b: TypeRef[], shapes: DocumentShapes, seen: Set<string>): boolean {\n  return a.length === b.length && a.every((variant, i) => sameShapeWithin(variant, b[i], shapes, seen));\n}\n\n/** The same `property`, the same mapping keys, each mapped to one shape; absent on both sides is the same too. */\nfunction sameDiscriminator(\n  a: { property: string; mapping: Record<string, string> } | undefined,\n  b: { property: string; mapping: Record<string, string> } | undefined,\n  shapes: DocumentShapes,\n  seen: Set<string>,\n): boolean {\n  if (!a && !b) return true;\n  if (!a || !b || a.property !== b.property) return false;\n  const aKeys = Object.keys(a.mapping).sort();\n  const bKeys = Object.keys(b.mapping).sort();\n  if (aKeys.length !== bKeys.length || !aKeys.every((key, i) => key === bKeys[i])) return false;\n  return aKeys.every((key) =>\n    sameShapeWithin({ kind: 'model', name: a.mapping[key] }, { kind: 'model', name: b.mapping[key] }, shapes, seen),\n  );\n}\n\nfunction sameEnumShape(a: Enum, b: Enum): boolean {\n  const values = (entry: Enum): string =>\n    entry.values\n      .map((value) => stableStringify(omitKeys(value, ENUM_VALUE_DOC_KEYS)))\n      .sort()\n      .join('|');\n  return values(a) === values(b) && (a.default ?? null) === (b.default ?? null) && !!a.deprecated === !!b.deprecated;\n}\n\n/** The entries of `value` whose key is not in `keys` and whose value is set. */\nfunction omitKeys(value: object, keys: ReadonlySet<string>): Record<string, unknown> {\n  return Object.fromEntries(\n    Object.entries(value).filter(([key, entryValue]) => entryValue !== undefined && !keys.has(key)),\n  );\n}\n\n/** `JSON.stringify` with object keys sorted and unset entries dropped, so equal shapes serialize equally. */\nfunction stableStringify(value: unknown): string {\n  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n  if (value !== null && typeof value === 'object') {\n    const record = value as Record<string, unknown>;\n    const entries = Object.keys(record)\n      .filter((key) => record[key] !== undefined)\n      .sort()\n      .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`);\n    return `{${entries.join(',')}}`;\n  }\n  return JSON.stringify(value) ?? 'undefined';\n}\n","import type { RequestBodyContent, ResponseContent, TypeRef } from '../ir/types.js';\nimport { mediaTypeEssence, parseMediaType } from '../utils/media-type.js';\nimport type { RequestBodyContentTypesChange } from './types.js';\nimport { sameShape, type DocumentShapes } from './shapes.js';\n\n/**\n * One media type a request body or a response entry declares, as the differ\n * compares it. Media types are compared by essence — `type/subtype`, case\n * folded, parameters stripped (`mediaTypeEssence`, the parser's own rule for\n * typing a body) — so `Text/HTML` is `text/html` and\n * `application/problem+json; charset=utf-8` is `application/problem+json`,\n * while a change is reported with the key as written in the document that\n * declares it.\n */\nexport interface MediaTypeBody {\n  /** The key as written in its document (`Text/HTML`), which is what a change reports. */\n  mediaType: string;\n  /** `mediaTypeEssence(mediaType)`: what decides which key of the other document this one is. */\n  essence: string;\n  /** `mediaTypeParameters(mediaType)`: the parameters that may select another representation, as sorted name/value pairs. */\n  parameters: Array<[string, string]>;\n  /** The body's type, when the entry's contents carry one for this key. */\n  type?: TypeRef;\n  /**\n   * Whether this is the entry's own body — the one its `type` (a response\n   * entry's) or `requestBody` was read from: the content entry that shares\n   * that very object (how the parser builds it), or, for an error that\n   * carries no lists, the implicit `application/json` entry restored from\n   * `type`. Never decided by structural equality, which a secondary body can\n   * coincidentally satisfy. No body is the own one for a 3xx, for a request\n   * body none of whose media types is read, or in a hand-built IR without\n   * that identity.\n   */\n  own: boolean;\n}\n\n/**\n * The bodies of one entry, one per `contentTypes` entry, each with the\n * `contents` entry written under the same key. `ownType` marks the own body\n * by object identity; `ownEssence` is the error-only fallback for an IR\n * whose lists do not share `type`'s object: the first body of that essence\n * (`application/json`, the media type an error's `type` is read from).\n */\nexport function mediaTypeBodies(\n  contentTypes: string[],\n  contents: Array<ResponseContent | RequestBodyContent>,\n  ownType: TypeRef | undefined,\n  ownEssence?: string,\n): MediaTypeBody[] {\n  const own =\n    ownType &&\n    (contents.find((c) => c.type === ownType) ??\n      (ownEssence ? contents.find((c) => mediaTypeEssence(c.contentType) === ownEssence) : undefined));\n  return contentTypes.map((mediaType) => {\n    const content = contents.find((c) => c.contentType === mediaType);\n    return {\n      mediaType,\n      essence: mediaTypeEssence(mediaType),\n      parameters: mediaTypeParameters(mediaType),\n      ...(content ? { type: content.type } : {}),\n      own: content !== undefined && content === own,\n    };\n  });\n}\n\n/**\n * A media type's parameters other than `charset`, in one form whatever the\n * spelling: each parameter as `parseMediaType` reads it — name lower-cased,\n * quoted value decoded, so a `;` inside the quotes is part of the value and\n * `profile=\"print\"` is `profile=print` — as `[name, value]` pairs sorted by\n * name, then value. So `application/pdf; version=1.7` reads\n * `[['version', '1.7']]`, `text/html; Charset=UTF-8` and `text/html` both\n * read `[]`, and `; a=1; b=2` is `; b=2 ;a=1`. The pairs stay structured\n * (compared JSON-encoded, never joined into one string), so `title=\"report;\n * version=2\"` — one parameter — and `title=report; version=2` — two — are\n * different parameters. `charset` is left out because it never selects\n * another representation of a JSON or text body (RFC 8259 §8.1 has no\n * charset for JSON at all); any other parameter — `version`, `profile` —\n * may, which is what `reparameterized` reports.\n */\nexport function mediaTypeParameters(contentType: string): Array<[string, string]> {\n  return parseMediaType(contentType)\n    .parameters.filter((parameter) => parameter.name !== 'charset')\n    .map((parameter): [string, string] => [parameter.name, parameter.value])\n    .sort(([aName, aValue], [bName, bValue]) =>\n      aName < bName ? -1 : aName > bName ? 1 : aValue < bValue ? -1 : aValue > bValue ? 1 : 0,\n    );\n}\n\n/**\n * The pairs whose parameters other than `charset` differ\n * (`mediaTypeParameters`, compared as structured pairs): the body is typed\n * the same on both sides, but the new spelling may select another\n * representation (`application/pdf; version=1.7` → `; version=2.0`), so it\n * is reported — additive, since callers can still ask for the essence and\n * the shape did not change.\n */\nexport function reparameterizedBodies(\n  pairs: Array<[MediaTypeBody, MediaTypeBody]>,\n): Array<[MediaTypeBody, MediaTypeBody]> {\n  return pairs.filter(([before, after]) => !sameParameters(before, after));\n}\n\n/** A reparameterized pair as a change reports it: both spellings, as written in their specs. */\nexport function respelling([before, after]: [MediaTypeBody, MediaTypeBody]): { from: string; to: string } {\n  return { from: before.mediaType, to: after.mediaType };\n}\n\n/** How the media types of one body compare between two specs, each side as written in its spec. */\nexport interface MediaTypeBodiesDiff {\n  /** Every body both specs declare, old beside new, in the new spec's order. */\n  pairs: Array<[MediaTypeBody, MediaTypeBody]>;\n  added: MediaTypeBody[];\n  removed: MediaTypeBody[];\n}\n\n/**\n * Which item of the old list each item of the new list is, for two lists\n * whose items are matched by a folded name — a response entry's headers by\n * case-folded name, as HTTP compares them (`foldHeaderName`: `X-Rate-Limit`\n * is `x-rate-limit`). Two names of one folding declared side by side\n * (`X-Foo` beside `x-foo`, which the parser keeps apart only in a hand-built\n * IR) never collapse into one: a new item claims the old item spelled\n * exactly as it is, else the first old item of its folding that nothing\n * claimed, in document order. What is left on the new side was `added`;\n * what is left on the old side was `removed`. Every pair is in the new\n * list's order. `pairMediaTypeBodies` below pairs an entry's media types\n * the same way at its first and last tiers, with parameter and shape tiers\n * of its own between them.\n */\nexport function pairByName<T>(\n  oldItems: T[],\n  newItems: T[],\n  written: (item: T) => string,\n  folded: (item: T) => string,\n): { pairs: Array<[T, T]>; added: T[]; removed: T[] } {\n  const unclaimed = new Set(oldItems);\n  const claim = (matches: (old: T) => boolean): T | undefined => {\n    for (const old of oldItems) {\n      if (!unclaimed.has(old) || !matches(old)) continue;\n      unclaimed.delete(old);\n      return old;\n    }\n    return undefined;\n  };\n  // Exact spellings claim first, whatever their position, so a respelled\n  // name never takes the old item an unchanged name still names.\n  const bySpelling = new Map<T, T>();\n  for (const item of newItems) {\n    const old = claim((candidate) => written(candidate) === written(item));\n    if (old) bySpelling.set(item, old);\n  }\n  const pairs: Array<[T, T]> = [];\n  const added: T[] = [];\n  for (const item of newItems) {\n    const old = bySpelling.get(item) ?? claim((candidate) => folded(candidate) === folded(item));\n    if (old) pairs.push([old, item]);\n    else added.push(item);\n  }\n  return { pairs, added, removed: oldItems.filter((old) => unclaimed.has(old)) };\n}\n\n/**\n * Which body of the old entry each body of the new entry is, so the two\n * entries' media types compare by essence the way the parser types them —\n * `Text/HTML` is `text/html`, `application/problem+json; charset=utf-8` is\n * `application/problem+json` — without two keys of one essence declared side\n * by side (`application/json` beside `application/json; charset=utf-8`)\n * collapsing into one. Bodies pair in a strict order of preference, each\n * tier run over every new body before the next, so a later tier never takes\n * an old body an earlier one would still name: (1) the old body spelled\n * exactly the same; (2) one of the same essence with the same parameters\n * other than `charset` (`mediaTypeParameters`), so `Application/YAML;\n * version=1` is still `application/yaml; version=1` wherever it moved; (3)\n * one of the same essence whose body is the same shape (`sameShape` through\n * `shapes`), so a key that only edited a parameter finds its body; (4) one\n * of the same essence, in document order. What is left on the new side was\n * `added`; what is left on the old side was `removed`. Every pair is in the\n * new entry's order.\n */\nexport function pairMediaTypeBodies(\n  oldBodies: MediaTypeBody[],\n  newBodies: MediaTypeBody[],\n  shapes?: DocumentShapes,\n): MediaTypeBodiesDiff {\n  const unclaimed = new Set(oldBodies);\n  const pairedTo = new Map<MediaTypeBody, MediaTypeBody>();\n  const tiers: Array<(before: MediaTypeBody, after: MediaTypeBody) => boolean> = [\n    (before, after) => before.mediaType === after.mediaType,\n    (before, after) => before.essence === after.essence && sameParameters(before, after),\n    (before, after) =>\n      before.essence === after.essence &&\n      before.type !== undefined &&\n      after.type !== undefined &&\n      sameShape(before.type, after.type, shapes),\n    (before, after) => before.essence === after.essence,\n  ];\n  for (const matches of tiers) {\n    for (const after of newBodies) {\n      if (pairedTo.has(after)) continue;\n      const before = oldBodies.find((candidate) => unclaimed.has(candidate) && matches(candidate, after));\n      if (!before) continue;\n      unclaimed.delete(before);\n      pairedTo.set(after, before);\n    }\n  }\n  const pairs: Array<[MediaTypeBody, MediaTypeBody]> = [];\n  const added: MediaTypeBody[] = [];\n  for (const after of newBodies) {\n    const before = pairedTo.get(after);\n    if (before) pairs.push([before, after]);\n    else added.push(after);\n  }\n  return { pairs, added, removed: oldBodies.filter((old) => unclaimed.has(old)) };\n}\n\n/** Whether two bodies declare the same parameters other than `charset`, as structured pairs. */\nfunction sameParameters(a: MediaTypeBody, b: MediaTypeBody): boolean {\n  return JSON.stringify(a.parameters) === JSON.stringify(b.parameters);\n}\n\n/**\n * The pairs whose body types are not one shape (`sameShape`, so a model that\n * was only renamed — as the parser does when a parameter edit on a key\n * declared beside another spelling of its essence renames the model it mints\n * — is no retype; by name alone without `shapes`), except the own body on\n * both sides when `ownCoveredElsewhere`: another comparison\n * (`responseChanged`, `errorsChanged`, `requestBodyChanged`) reports that\n * very retype.\n */\nexport function retypedBodies(\n  pairs: Array<[MediaTypeBody, MediaTypeBody]>,\n  ownCoveredElsewhere: boolean,\n  shapes?: DocumentShapes,\n): Array<[MediaTypeBody, MediaTypeBody]> {\n  return pairs.filter(([before, after]) => {\n    if (!before.type || !after.type || sameShape(before.type, after.type, shapes)) return false;\n    return !(before.own && after.own && ownCoveredElsewhere);\n  });\n}\n\n/** The request-body fields a media-type comparison reads, shared by `Operation` and `Webhook`. */\nexport interface RequestBodyMediaTypes {\n  requestBody?: TypeRef;\n  requestBodyContentTypes?: string[];\n  requestBodyContents?: RequestBodyContent[];\n}\n\n/**\n * Whose side a request body's media types are judged from: the caller's for\n * an operation (it sends the body), the receiver's for a webhook (its\n * handler decodes the body the sender chose).\n */\nexport type RequestBodySide = 'caller' | 'receiver';\n\n/**\n * How the media types of an operation's or a webhook's request body changed:\n * its `content` keys, paired by essence exactly as a response entry's are\n * (`pairMediaTypeBodies`), each reported as written in the spec that\n * declares it. Compared only while both specs declare a body — one\n * appearing or disappearing is `requestBodyChanged`'s — and the body\n * `requestBody` was read from (the entry that shares its object) is left to\n * `requestBodyChanged` when it changes type, so a retype here is always a\n * secondary media type's. Classified from `side`: for the caller, a media\n * type it could send that is gone or whose body changed type is breaking and\n * one it can newly send is additive; for the receiver, one the sender can\n * newly use or whose body changed type is breaking (the handler must decode\n * it) and one the sender can no longer use is additive. A retype is a body\n * whose shape changed (`sameShape` through `shapes`, the two documents'\n * named types), not one whose model was only renamed. A pair whose\n * parameters other than `charset` differ is `reparameterized`, additive on\n * either side. `undefined` when nothing changed.\n */\nexport function diffRequestBodyContentTypes(\n  oldBody: RequestBodyMediaTypes,\n  newBody: RequestBodyMediaTypes,\n  side: RequestBodySide,\n  shapes?: DocumentShapes,\n): RequestBodyContentTypesChange | undefined {\n  if (!declaresBody(oldBody) || !declaresBody(newBody)) return undefined;\n  const { pairs, added, removed } = pairMediaTypeBodies(requestBodyBodies(oldBody), requestBodyBodies(newBody), shapes);\n  const retyped = retypedBodies(pairs, true, shapes);\n  const reparameterized = reparameterizedBodies(pairs);\n  if (added.length === 0 && removed.length === 0 && retyped.length === 0 && reparameterized.length === 0) {\n    return undefined;\n  }\n  const breaking = retyped.length > 0 || (side === 'caller' ? removed.length > 0 : added.length > 0);\n  return {\n    added: added.map((body) => body.mediaType),\n    removed: removed.map((body) => body.mediaType),\n    retyped: retyped.map(([, after]) => after.mediaType),\n    reparameterized: reparameterized.map(respelling),\n    classification: breaking ? 'breaking' : 'additive',\n  };\n}\n\n/** Whether a body is declared at all: a type was read from it, or it lists media types none of which is read. */\nfunction declaresBody(body: RequestBodyMediaTypes): boolean {\n  return body.requestBody !== undefined || body.requestBodyContentTypes !== undefined;\n}\n\n/** A request body's media types as the differ compares them, the one `requestBody` was read from marked `own`. */\nfunction requestBodyBodies(body: RequestBodyMediaTypes): MediaTypeBody[] {\n  return mediaTypeBodies(body.requestBodyContentTypes ?? [], body.requestBodyContents ?? [], body.requestBody);\n}\n\n/**\n * Whether the representation one side's `requestBody` is read from — the\n * media type, with its shape — is one the other side declares with an\n * unchanged shape. Which side's is judged from `side`, as\n * `diffRequestBodyContentTypes` is: for the caller (an operation), the old\n * spec's own body must still be declared by the new spec, since an SDK\n * built for the old spec keeps sending it; for the receiver (a webhook),\n * the new spec's own body must already have been declared by the old spec,\n * since the handler built for it decodes only what it declared. The two\n * sides are always paired old against new (`pairMediaTypeBodies`, exactly\n * as the media-type diff pairs them) and compared old against new\n * (`sameShape` through `shapes`, the two documents' named types; by name\n * alone without them), so the documents are never looked up the wrong way\n * round for either side. This decides whether an encoding shift\n * (`requestBodyEncodingShift`) breaks that side of the wire. `false` when\n * the judged side marks no own body — no media-type lists, or none read as\n * `requestBody` — so a hand-built IR without lists keeps the breaking\n * reading.\n */\nexport function ownRepresentationKept(\n  oldBody: RequestBodyMediaTypes,\n  newBody: RequestBodyMediaTypes,\n  side: RequestBodySide,\n  shapes?: DocumentShapes,\n): boolean {\n  const oldBodies = requestBodyBodies(oldBody);\n  const newBodies = requestBodyBodies(newBody);\n  const own = (side === 'caller' ? oldBodies : newBodies).find((body) => body.own);\n  if (!own?.type) return false;\n  const pair = pairMediaTypeBodies(oldBodies, newBodies, shapes).pairs.find(\n    ([before, after]) => (side === 'caller' ? before : after) === own,\n  );\n  if (!pair) return false;\n  const [before, after] = pair;\n  return before.type !== undefined && after.type !== undefined && sameShape(before.type, after.type, shapes);\n}\n","import type { Parameter } from '../ir/types.js';\nimport { parameterKey } from '../ir/parameter-key.js';\nimport { mediaTypeEssence } from '../utils/media-type.js';\nimport type { ParamLocation } from './types.js';\n\n/** A parameter tagged with where it lives, as `locatedParams` yields it. */\nexport interface LocatedParam {\n  p: Parameter;\n  loc: ParamLocation;\n}\n\n/**\n * The parameter lists an operation or a webhook carries, by location.\n * `Operation` has all four (`cookieParams` only when the document declares\n * one); `Webhook` has no `pathParams`.\n */\nexport interface ParamCarrier {\n  pathParams?: Parameter[];\n  queryParams: Parameter[];\n  headerParams: Parameter[];\n  cookieParams?: Parameter[];\n}\n\n/**\n * Every parameter an operation or a webhook carries, each tagged with its\n * location, in one fixed order: path, query, header, cookie. `diffParams`\n * (operations) and `diffWebhookParams` (webhooks) both build their two sides\n * from this walk, so a location the IR carries is never compared on one node\n * and skipped on the other — an operation's cookie parameters were (#294).\n *\n * `Operation.bodyOwnedQueryParams` is not walked. Those are query parameters\n * the request body also declares as properties, on a body-carrying method;\n * they travel in the body only and no emitter serializes them to the URL,\n * so the differ compares them as fields of the body's model, and a query\n * parameter the body takes over is reported as `param-removed` at `query`.\n */\nexport function locatedParams(node: ParamCarrier): LocatedParam[] {\n  const tagged = (loc: ParamLocation, params: Parameter[] | undefined): LocatedParam[] =>\n    (params ?? []).map((p) => ({ p, loc }));\n  return [\n    ...tagged('path', node.pathParams),\n    ...tagged('query', node.queryParams),\n    ...tagged('header', node.headerParams),\n    ...tagged('cookie', node.cookieParams),\n  ];\n}\n\n/**\n * The key a parameter is matched on between two specs. OpenAPI allows a path\n * `id` beside a query `id` on one operation, and a webhook's header and query\n * parameters may share a name, so the name alone does not identify one\n * (#261): the location is joined to it. Header names are case-insensitive\n * (RFC 9110 §5.1), so a header's name is folded before it is joined (#295).\n * The rule is `parameterKey` in `ir/parameter-key.ts`, the identity the\n * parser merges a path item's parameters with an operation's on, so what the\n * parser reads as one parameter the differ pairs as one.\n */\nexport function paramKey(loc: ParamLocation, name: string): string {\n  return parameterKey(loc, name);\n}\n\n/** The two sides of a parameter's `contentType`, carried on the `param-content-type-changed` entry that reports them. */\nexport interface ParameterContentTypeShift {\n  /** The old spec's `content` key as written, or `null` for a parameter typed by `schema`. */\n  oldContentType: string | null;\n  /** The new spec's `content` key as written, or `null` for a parameter typed by `schema`. */\n  newContentType: string | null;\n  /** `content type <schema> → application/json`, each side as written. */\n  details: string;\n}\n\n/**\n * How a paired parameter's `Parameter.contentType` differs between two\n * specs, or `undefined` when it does not. The media type decides how the\n * value is serialized — a `content` parameter's value is sent in that media\n * type, a `schema` parameter's by `style`/`explode` — so a parameter that\n * moves between `schema` and `content`, or between two media types that\n * differ in essence (`application/json` → `text/plain`), is a change even\n * when its type did not move. The two keys are compared by essence\n * (`mediaTypeEssence`: `type/subtype`, case folded, parameters stripped),\n * since neither case nor a parameter such as `charset` changes how the\n * value is encoded; both are carried as written. `diffParams` (operations)\n * and `diffWebhookParams` (webhooks) report it through this one rule.\n */\nexport function parameterContentTypeShift(\n  oldParam: Parameter,\n  newParam: Parameter,\n): ParameterContentTypeShift | undefined {\n  const oldContentType = oldParam.contentType ?? null;\n  const newContentType = newParam.contentType ?? null;\n  const same =\n    oldContentType === null || newContentType === null\n      ? oldContentType === newContentType\n      : mediaTypeEssence(oldContentType) === mediaTypeEssence(newContentType);\n  if (same) return undefined;\n  return {\n    oldContentType,\n    newContentType,\n    details: `content type ${oldContentType ?? '<schema>'} → ${newContentType ?? '<schema>'}`,\n  };\n}\n","import type {\n  ApiSpec,\n  ErrorResponse,\n  Operation,\n  PaginationEndOfIteration,\n  ResponseContent,\n  ResponseHeader,\n  ServerEntry,\n  StatusRange,\n  TypeRef,\n} from '../ir/types.js';\nimport { foldHeaderName } from '../ir/parameter-key.js';\nimport { resolveServerUrl } from '../ir/server-url.js';\nimport { diffServers } from './servers.js';\nimport {\n  diffRequestBodyContentTypes,\n  ownRepresentationKept,\n  mediaTypeBodies,\n  pairByName,\n  pairMediaTypeBodies,\n  reparameterizedBodies,\n  respelling,\n  retypedBodies,\n  type MediaTypeBody,\n} from './media-types.js';\nimport type { DocumentShapes } from './shapes.js';\nimport type {\n  Change,\n  FieldChange,\n  ParamChange,\n  ParamLocation,\n  ResponseContentTypesChange,\n  ResponseHeaderChange,\n  ServerChange,\n} from './types.js';\nimport { locatedParams, paramKey, parameterContentTypeShift } from './params.js';\nimport {\n  classifyFieldChange,\n  classifyParamChange,\n  classifyResponseHeaderChange,\n  deprecationDetails,\n  deprecationFlip,\n  extensionsShift,\n  parameterNameShift,\n  requestBodyEncodingShift,\n  tagsShift,\n} from './classify.js';\nimport { formatChangeDetails, primitivesDifferOnlyByFormat, typeRefsEqual } from './models.js';\nimport { classifySecurityChange, securityShift, type DocumentSecurity } from './security.js';\n\n/**\n * The two documents' `servers`, so `diffOperations` can resolve what an\n * operation is actually served from (`op.servers ?? document servers`).\n * `diffSpecs` supplies it; a direct caller may leave it out, in which case an\n * operation that inherits is compared as having no servers at all — which is\n * OpenAPI's default, `/`, and the same thing (#291).\n */\nexport interface DocumentServers {\n  old: ServerEntry[] | undefined;\n  new: ServerEntry[] | undefined;\n}\n\n/**\n * `documentSecurity` — the two documents' `security` — lets an operation that\n * declares none of its own be compared on what it inherits, exactly as\n * `documentServers` does for `servers`; `diffSpecs` passes both, a direct\n * caller may leave either out.\n */\nexport function diffOperations(\n  serviceName: string,\n  oldOps: Operation[],\n  newOps: Operation[],\n  documentServers?: DocumentServers,\n  documentSecurity?: DocumentSecurity,\n  shapes?: DocumentShapes,\n): Change[] {\n  const changes: Change[] = [];\n  const oldByName = new Map(oldOps.map((o) => [o.name, o]));\n  const newByName = new Map(newOps.map((o) => [o.name, o]));\n\n  for (const [name] of newByName) {\n    if (!oldByName.has(name)) {\n      changes.push({\n        kind: 'operation-added',\n        serviceName,\n        operationName: name,\n        classification: 'additive',\n      });\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push({\n        kind: 'operation-removed',\n        serviceName,\n        operationName: name,\n        classification: 'breaking',\n      });\n    }\n  }\n\n  for (const [name, newOp] of newByName) {\n    const oldOp = oldByName.get(name);\n    if (!oldOp) continue;\n\n    const paramChanges = diffParams(oldOp, newOp);\n    const responseChanged = !typeRefsEqual(oldOp.response, newOp.response);\n    const requestBodyChanged = !requestBodiesEqual(oldOp.requestBody, newOp.requestBody);\n    // The required flag and the encoding are compared only while both sides\n    // carry a body: a body appearing or disappearing is already\n    // `requestBodyChanged`, and the parser sets both beside the body, so\n    // they go with it.\n    const bothCarryBody = !!oldOp.requestBody && !!newOp.requestBody;\n    // An absent flag reads as optional, as it does in OpenAPI.\n    const requestBodyRequiredChanged =\n      bothCarryBody && (oldOp.requestBodyRequired ?? false) !== (newOp.requestBodyRequired ?? false);\n    // The wire format the SDK serializes the body as, read through the\n    // function `diffWebhooks` reads a payload's encoding with, which\n    // compares only while both sides carry a body, likewise.\n    const encoding = requestBodyEncodingShift(oldOp, newOp);\n    const requestBodyEncodingChanged = encoding !== undefined;\n    // The media types callers may send the body as, only while both sides\n    // declare a body, likewise; judged from the caller's side, which sends\n    // it. A body moving from JSON to a form media type sets this beside the\n    // encoding flag: the JSON media type is removed and the form one added.\n    const requestBodyContentTypeChange = diffRequestBodyContentTypes(oldOp, newOp, 'caller', shapes);\n    const requestBodyContentTypesChanged = requestBodyContentTypeChange !== undefined;\n    const httpMethodChanged = oldOp.httpMethod !== newOp.httpMethod;\n    const pathChanged = oldOp.path !== newOp.path;\n    const paginatedChanged = !!oldOp.pagination !== !!newOp.pagination;\n    // Only comparable when both versions paginate; presence is paginatedChanged's job.\n    const oldPagination = oldOp.pagination;\n    const newPagination = newOp.pagination;\n    const bothPaginated = !!oldPagination && !!newPagination;\n    const paginationFieldChanged = (field: 'strategy' | 'param' | 'limitParam' | 'dataPath' | 'pageStart'): boolean =>\n      bothPaginated && oldPagination?.[field] !== newPagination?.[field];\n    const paginationStrategyChanged = paginationFieldChanged('strategy');\n    const paginationParamChanged = paginationFieldChanged('param');\n    const paginationLimitParamChanged = paginationFieldChanged('limitParam');\n    const paginationDataPathChanged = paginationFieldChanged('dataPath');\n    const paginationPageStartChanged = paginationFieldChanged('pageStart');\n    const paginationEndOfIterationChanged =\n      bothPaginated && !endOfIterationEqual(oldPagination?.endOfIteration, newPagination?.endOfIteration);\n    const injectIdempotencyKeyChanged = oldOp.injectIdempotencyKey !== newOp.injectIdempotencyKey;\n    const errorsDiff = classifyErrorsChange(oldOp.errors, newOp.errors);\n    const errorsChanged = errorsDiff !== 'none';\n    const responseContentTypeChanges = diffResponseContentTypes(oldOp, newOp, shapes);\n    const responseContentTypesChanged = responseContentTypeChanges.length > 0;\n    // The headers each response entry declares, which an SDK may expose as\n    // typed accessors on a response wrapper (#296).\n    const responseHeaderChanges = diffResponseHeaders(oldOp, newOp);\n    const responseHeadersChanged = responseHeaderChanges.length > 0;\n    // The status code `response` is read from (`responseStatusCode`, present\n    // exactly when a 2xx or 3xx is declared), compared only while both sides\n    // carry one, as `requestBodyRequired` is while both carry a body: an\n    // operation gaining or losing its only 2xx/3xx is not a move. Reported\n    // as additive: the old code may still be declared (a `200` added beside\n    // a lone `201` makes the `200` the primary), and whether a bare status\n    // move breaks callers is left to a separate issue.\n    const bothCarryStatus = oldOp.responseStatusCode !== undefined && newOp.responseStatusCode !== undefined;\n    const responseStatusCodeChanged = bothCarryStatus && oldOp.responseStatusCode !== newOp.responseStatusCode;\n    const status = responseStatusCodeChanged\n      ? { oldResponseStatusCode: oldOp.responseStatusCode, newResponseStatusCode: newOp.responseStatusCode }\n      : {};\n    const fallbackDiff = classifyFallbackResponsesChange(oldOp, newOp);\n    const fallbackResponsesChanged = fallbackDiff !== 'none';\n    // Additive either way: the operation's signature is unchanged, but a\n    // changelog has to say it, so a flipped flag alone is a change.\n    const deprecation = deprecationFlip(oldOp, newOp);\n    const deprecatedChanged = deprecation !== undefined;\n    // `servers` is set only when the operation's effective servers differ from\n    // the document's. Absent on both sides is \"inherits\" twice — a moved\n    // document is the document-level diff's to report. Otherwise the lists the\n    // operation is actually served from are compared, so a document that moves\n    // to where the operation already pointed (its override vanishes) is no\n    // change to the operation. Each change keeps the classification the\n    // document-level diff gives it (#299).\n    const serverChanges =\n      !!oldOp.servers || !!newOp.servers\n        ? effectiveServerChanges(\n            oldOp.servers ?? documentServers?.old ?? [],\n            newOp.servers ?? documentServers?.new ?? [],\n          )\n        : [];\n    const serversChanged = serverChanges.length > 0;\n    // What the operation's requests must carry, `op.security ?? document\n    // security` on each side, by the same rule as `servers`: absent on both\n    // sides inherits twice and is the document-level diff's to report.\n    const security = securityShift(oldOp, newOp, documentSecurity);\n    const securityChanged = security !== undefined;\n    // Additive always: tags group and document the method and change nothing\n    // a caller compiles against, but a changelog has to say it.\n    const tags = tagsShift(oldOp, newOp);\n    const tagsChanged = tags !== undefined;\n    // Additive always, as a flipped flag is: the operation's own extensions\n    // are not shape, but an emitter may read one, so a changelog has to say\n    // it. The flag is present only when they differ (`extensionsShift`).\n    const extensions = extensionsShift(oldOp, newOp);\n    const extensionsChanged = extensions !== undefined;\n    // The list envelope's fields, matched by name while both specs paginate:\n    // a scalar companion (`has_more`) sits on no model `diffModels` reads, so\n    // its extensions are compared here; a companion object's model is\n    // compared in the models diff (workos/oagen#369 round 2).\n    const envelopeFieldChanges = bothPaginated ? diffEnvelopeFieldExtensions(oldPagination, newPagination) : [];\n    const envelopeFieldsChanged = envelopeFieldChanges.length > 0;\n\n    const hasChanges =\n      paramChanges.length > 0 ||\n      responseChanged ||\n      requestBodyChanged ||\n      requestBodyRequiredChanged ||\n      requestBodyEncodingChanged ||\n      requestBodyContentTypesChanged ||\n      httpMethodChanged ||\n      pathChanged ||\n      paginatedChanged ||\n      paginationStrategyChanged ||\n      paginationParamChanged ||\n      paginationLimitParamChanged ||\n      paginationDataPathChanged ||\n      paginationPageStartChanged ||\n      paginationEndOfIterationChanged ||\n      injectIdempotencyKeyChanged ||\n      errorsChanged ||\n      responseContentTypesChanged ||\n      responseHeadersChanged ||\n      responseStatusCodeChanged ||\n      fallbackResponsesChanged ||\n      deprecatedChanged ||\n      serversChanged ||\n      securityChanged ||\n      tagsChanged ||\n      extensionsChanged ||\n      envelopeFieldsChanged;\n\n    if (hasChanges) {\n      // paginated: false→true is additive (SDK gains pagination helper)\n      // paginated: true→false is breaking (SDK loses pagination helper)\n      const paginatedBreaking = paginatedChanged && !newOp.pagination;\n      // endOfIteration: unset→set is additive (the iterator stops one request\n      // sooner); set→changed or set→unset is breaking (it stops at a different\n      // point than callers observed before)\n      const paginationEndOfIterationBreaking = paginationEndOfIterationChanged && !!oldPagination?.endOfIteration;\n      // injectIdempotencyKey: false→true is additive (SDK gains idempotency key)\n      // injectIdempotencyKey: true→false is breaking (SDK loses idempotency key)\n      const injectIdempotencyKeyBreaking = injectIdempotencyKeyChanged && !newOp.injectIdempotencyKey;\n      // requestBodyRequired: false→true is breaking (callers must now send the body)\n      // requestBodyRequired: true→false is additive (callers may now omit it)\n      const requestBodyRequiredBreaking = requestBodyRequiredChanged && !!newOp.requestBodyRequired;\n      // requestBody: a body appearing as optional is additive — callers gain an\n      // argument they may leave out, like an optional `param-added`. A body\n      // appearing as required, a body disappearing, and a body changing type\n      // are breaking. An absent flag reads as optional, as it does in OpenAPI.\n      const optionalRequestBodyAdded = !oldOp.requestBody && !!newOp.requestBody && !newOp.requestBodyRequired;\n      const requestBodyBreaking = requestBodyChanged && !optionalRequestBodyAdded;\n      // requestBodyEncoding: an SDK built for the old spec keeps sending the\n      // representation that spec's body was read from. Breaking when the new\n      // spec no longer accepts it — that media type gone, or its shape\n      // changed; additive when it still does, as when a media type the\n      // parser prefers is added beside it (`application/json` beside a kept\n      // `application/x-www-form-urlencoded`). A body without media-type\n      // lists reads as breaking.\n      const requestBodyEncodingBreaking =\n        requestBodyEncodingChanged && !ownRepresentationKept(oldOp, newOp, 'caller', shapes);\n      const errorsBreaking = errorsDiff === 'breaking';\n      // A media type callers could ask for that is gone, or a secondary body\n      // that changed shape, breaks them; one they can newly ask for, or one\n      // that only changed a parameter, does not.\n      const responseContentTypesBreaking = responseContentTypeChanges.some((c) => c.classification === 'breaking');\n      // A header the SDK exposed that is gone, retyped or no longer always\n      // sent breaks the code that read it; one added, respelled, deprecated\n      // or now always sent does not.\n      const responseHeadersBreaking = responseHeaderChanges.some((c) => c.classification === 'breaking');\n      // A media type callers could send that is gone, or a secondary body\n      // that changed shape, breaks them; one they can newly send does not.\n      const requestBodyContentTypesBreaking = requestBodyContentTypeChange?.classification === 'breaking';\n      const fallbackBreaking = fallbackDiff === 'breaking';\n      // servers: breaking exactly when the same edit to the document's\n      // `servers` would be — a server the callers could use is gone or its\n      // resolved URL moved; an entry, a variable or an enum value added, an\n      // enum lifted, or a variable the template never references changed, is\n      // additive (#299).\n      const serversBreaking = serverChanges.some((c) => c.classification === 'breaking');\n      // security: breaking when a request built for the old requirements no\n      // longer satisfies the new ones, read from the caller's side.\n      const securityBreaking =\n        security !== undefined &&\n        classifySecurityChange(security.oldSecurity, security.newSecurity, 'caller') === 'breaking';\n\n      const hasBreaking =\n        responseChanged ||\n        requestBodyBreaking ||\n        requestBodyRequiredBreaking ||\n        requestBodyEncodingBreaking ||\n        httpMethodChanged ||\n        pathChanged ||\n        paginatedBreaking ||\n        // The iterator sends a different parameter, page size or first page,\n        // or reads a different array: a behavior change for every caller.\n        paginationStrategyChanged ||\n        paginationParamChanged ||\n        paginationLimitParamChanged ||\n        paginationDataPathChanged ||\n        paginationPageStartChanged ||\n        paginationEndOfIterationBreaking ||\n        injectIdempotencyKeyBreaking ||\n        errorsBreaking ||\n        responseContentTypesBreaking ||\n        responseHeadersBreaking ||\n        requestBodyContentTypesBreaking ||\n        fallbackBreaking ||\n        serversBreaking ||\n        securityBreaking ||\n        paramChanges.some((pc) => pc.classification === 'breaking');\n      changes.push({\n        kind: 'operation-modified',\n        serviceName,\n        operationName: name,\n        paramChanges,\n        responseChanged,\n        requestBodyChanged,\n        requestBodyRequiredChanged,\n        requestBodyEncodingChanged,\n        ...encoding,\n        requestBodyContentTypesChanged,\n        ...(requestBodyContentTypeChange ? { requestBodyContentTypeChange } : {}),\n        httpMethodChanged,\n        pathChanged,\n        paginatedChanged,\n        paginationStrategyChanged,\n        paginationParamChanged,\n        paginationLimitParamChanged,\n        paginationDataPathChanged,\n        paginationPageStartChanged,\n        paginationEndOfIterationChanged,\n        injectIdempotencyKeyChanged,\n        errorsChanged,\n        responseContentTypesChanged,\n        responseContentTypeChanges,\n        responseHeadersChanged,\n        responseHeaderChanges,\n        responseStatusCodeChanged,\n        ...status,\n        fallbackResponsesChanged,\n        deprecatedChanged,\n        ...deprecation,\n        serversChanged,\n        serverChanges,\n        securityChanged,\n        ...security,\n        tagsChanged,\n        ...tags,\n        ...(extensions ? { extensionsChanged: true, ...extensions } : {}),\n        ...(envelopeFieldsChanged ? { envelopeFieldChanges } : {}),\n        classification: hasBreaking ? 'breaking' : 'additive',\n      });\n    }\n  }\n\n  return changes;\n}\n\n/**\n * The envelope fields (`PaginationMeta.envelopeFields`) whose `extensions`\n * differ between two paginated versions, matched by field name: one\n * `field-extensions-changed` entry each, additive, with the two sides\n * beside it (`extensionsShift`). A field only one side declares is not\n * reported here — nothing else about an envelope field is compared by the\n * differ — and a companion object's model is compared in `diffModels`.\n */\nfunction diffEnvelopeFieldExtensions(\n  oldPagination: Operation['pagination'],\n  newPagination: Operation['pagination'],\n): FieldChange[] {\n  const oldFields = new Map((oldPagination?.envelopeFields ?? []).map((field) => [field.name, field]));\n  const changes: FieldChange[] = [];\n  for (const field of newPagination?.envelopeFields ?? []) {\n    const before = oldFields.get(field.name);\n    if (!before) continue;\n    const shift = extensionsShift(before, field);\n    if (shift) changes.push({ ...classifyFieldChange('field-extensions-changed', field.name), ...shift });\n  }\n  return changes;\n}\n\nfunction endOfIterationEqual(\n  a: PaginationEndOfIteration | undefined,\n  b: PaginationEndOfIteration | undefined,\n): boolean {\n  if (!a && !b) return true;\n  if (!a || !b) return false;\n  return a.kind === b.kind && a.path === b.path;\n}\n\n/**\n * What changed about an operation's effective server list, in a way a caller\n * notices: the document-level diff's own answer (`diffServers`, #255), read\n * off the two lists as if each were a document — `baseUrl` is the first\n * entry resolved, as the parser sets it — and returned as it reports it,\n * each change with its own classification (#299). Anything it reports is a\n * change: a moved default host (`base-url-changed`, so a reorder counts\n * exactly when it moves the first entry's resolved URL), a server added or\n * removed by `url` template, and any variable change — the additive ones\n * included (a new enum value, a new variable, a lifted enum), which the\n * caller tells apart from the breaking ones by their classification.\n * Descriptions on a server or a variable, enum order, a repeated enum value\n * and position do not count there, so they do not here; neither does a URL\n * spelling `normalizeServerUrl` folds (scheme and host case, a default port,\n * a bare authority's `/`). Neither does the spelling of OpenAPI's default\n * server (#291): a list that is empty and one that is `/` alone (description\n * and variables aside, since `/` references no variable) are the same list\n * there, so an operation served from `/` written out and one served from a\n * document that declares nothing are served from the same place.\n */\nfunction effectiveServerChanges(oldServers: ServerEntry[], newServers: ServerEntry[]): ServerChange[] {\n  return diffServers(asDocument(oldServers), asDocument(newServers));\n}\n\n/** A server list as the document-level diff reads a document: `baseUrl` is its first entry resolved, `''` without one. */\nfunction asDocument(servers: ServerEntry[]): Pick<ApiSpec, 'baseUrl' | 'servers'> {\n  return { baseUrl: servers.length > 0 ? resolveServerUrl(servers[0]).url : '', servers };\n}\n\n/**\n * One response entry's media types and headers, with what the parser left\n * off restored so the two specs' entries compare alike: an error that\n * declares only `application/json` with a schema carries no lists in the IR,\n * so its implicit JSON entry is restored from `type`; a response without\n * content has no bodies; one without `headers` has none. `contentEntries`\n * is the differ's one walk of every response kind an operation declares,\n * and `pairContentEntries` its one rule for which entry of the other spec\n * each is, so the media-type diff and the header diff compare the same\n * pairs.\n */\ninterface ContentEntry {\n  key: string;\n  statusCode?: number;\n  /** The fallback response this is, when it is one: `default` or a range. */\n  fallback?: 'default' | StatusRange;\n  /** The primary success response: the one `response` is the body of. */\n  isPrimary: boolean;\n  /** The entry's media types, one per `contentTypes` entry, in document order. */\n  bodies: MediaTypeBody[];\n  /** The headers the entry declares, in document order; `[]` when it declares none. */\n  headers: ResponseHeader[];\n  /**\n   * Whether another comparison reports a change to the own body when this\n   * entry is paired with one of its own kind: `responseChanged` for the\n   * primary, `errorsChanged` for an error. An alternate 2xx has none, so\n   * even its own body is compared here — and so is a primary's when it is\n   * paired with an alternate 2xx (the primary moved, or a lone 2xx paired\n   * with the entry that offers its media types), since `responseChanged`\n   * compares the two primaries, not that pair.\n   */\n  ownCoveredElsewhere: boolean;\n}\n\nconst JSON_MEDIA_TYPE = 'application/json';\n\n/**\n * Every response entry of an operation, keyed so the two specs' entries pair\n * up by status code: every 2xx/3xx entry as `success:<code>`, every error as\n * `error:<code>`, the `default` and each range response as\n * `fallback:<key>`. The primary success response (the one `response` is the\n * body of, read from the operation's own lists) is `success:<code>` too: the\n * entry of `responseStatusCode` when `successResponses` lists it — the\n * parser's own pick, so a primary that changes status still pairs with the\n * entry of its code — and, for a lone 2xx that `successResponses` does not\n * list, `responseStatusCode` itself, the code the parser read `response`\n * from, so a lone `201` pairs with the other spec's `201` whether that spec\n * declares it alone or beside a `200` it added. A primary that carries no\n * code — an operation declaring no 2xx/3xx at all, or a hand-built IR's\n * lone 2xx — is keyed `primary` (see `pairContentEntries` for what it pairs\n * with).\n */\nfunction contentEntries(op: Operation): ContentEntry[] {\n  const entries: ContentEntry[] = [];\n  const successes = [...(op.successResponses ?? [])].sort((a, b) => a.statusCode - b.statusCode);\n  // The entry `response` was read from: the one of `responseStatusCode`\n  // when the IR carries it, else — a hand-built IR without the code — the\n  // one that shares `response`'s content list or type.\n  const primaryEntry =\n    successes.find((entry) => entry.statusCode === op.responseStatusCode) ??\n    successes.find(\n      (entry) =>\n        (op.responseContents !== undefined && entry.contents === op.responseContents) ||\n        typeRefsEqual(entry.type, op.response),\n    );\n  const primaryStatus = primaryEntry?.statusCode ?? op.responseStatusCode;\n  // The primary's headers are `responseHeaders`, the same array as its\n  // `successResponses` entry's when both exist (how the parser builds it);\n  // a hand-built IR that sets only the entry's is read from the entry.\n  entries.push({\n    key: primaryStatus !== undefined ? `success:${primaryStatus}` : 'primary',\n    ...(primaryStatus !== undefined ? { statusCode: primaryStatus } : {}),\n    isPrimary: true,\n    bodies: mediaTypeBodies(op.responseContentTypes ?? [], op.responseContents ?? [], op.response),\n    headers: op.responseHeaders ?? primaryEntry?.headers ?? [],\n    ownCoveredElsewhere: true,\n  });\n  for (const entry of successes) {\n    if (entry === primaryEntry) continue;\n    entries.push({\n      key: `success:${entry.statusCode}`,\n      statusCode: entry.statusCode,\n      isPrimary: false,\n      bodies: mediaTypeBodies(entry.contentTypes ?? [], entry.contents ?? [], entry.type),\n      headers: entry.headers ?? [],\n      ownCoveredElsewhere: false,\n    });\n  }\n  for (const error of op.errors) {\n    const implicitJson: ResponseContent[] = error.type ? [{ contentType: JSON_MEDIA_TYPE, type: error.type }] : [];\n    entries.push({\n      key: `error:${error.statusCode}`,\n      statusCode: error.statusCode,\n      isPrimary: false,\n      bodies: mediaTypeBodies(\n        error.contentTypes ?? implicitJson.map((c) => c.contentType),\n        error.contents ?? implicitJson,\n        error.type,\n        JSON_MEDIA_TYPE,\n      ),\n      headers: error.headers ?? [],\n      ownCoveredElsewhere: true,\n    });\n  }\n  // A fallback's own body is its JSON entry, whose retype `fallbackResponsesChanged` reports.\n  const fallbacks: Array<\n    [\n      'default' | StatusRange,\n      { type?: TypeRef; contentTypes?: string[]; contents?: ResponseContent[]; headers?: ResponseHeader[] },\n    ]\n  > = [];\n  if (op.defaultResponse) fallbacks.push(['default', op.defaultResponse]);\n  for (const range of op.rangeResponses ?? []) fallbacks.push([range.range, range]);\n  for (const [fallback, entry] of fallbacks) {\n    entries.push({\n      key: `fallback:${fallback}`,\n      fallback,\n      isPrimary: false,\n      bodies: mediaTypeBodies(entry.contentTypes ?? [], entry.contents ?? [], entry.type),\n      headers: entry.headers ?? [],\n      ownCoveredElsewhere: true,\n    });\n  }\n  return entries;\n}\n\n/** `pairByName` over an entry's headers: spelled as written, folded as HTTP compares header names. */\nfunction pairResponseHeaders(\n  oldHeaders: ResponseHeader[],\n  newHeaders: ResponseHeader[],\n): { pairs: Array<[ResponseHeader, ResponseHeader]>; added: ResponseHeader[]; removed: ResponseHeader[] } {\n  return pairByName(\n    oldHeaders,\n    newHeaders,\n    (header) => header.name,\n    (header) => foldHeaderName(header.name),\n  );\n}\n\n/**\n * Per response entry both specs have, the headers the new spec added,\n * removed, retyped, re-required, respelled or deprecated, each change\n * carrying the entry's `statusCode` or `fallback`. Entries pair as\n * `diffResponseContentTypes` pairs them (`pairContentEntries`), so the entry\n * whose media types are compared with another's is the one whose headers\n * are; within an entry, headers pair by case-folded name\n * (`pairResponseHeaders`), so a header that only changed case is one header,\n * reported `header-name-changed`. A change is located at the entry of the\n * spec that declares what changed: a header removed at the old spec's\n * entry, one added or changed at the new spec's — so an operation that\n * lost its only 2xx, whose new primary carries no code, reports that\n * entry's headers under its old code, not nowhere. A 2xx the old spec declared and\n * the new does not has no other diff to report it, so each of its headers\n * is reported `header-removed`, as its media types are reported removed; an\n * error or fallback entry only one spec declares is the errors or fallback\n * diff's business, and a 2xx the new spec adds is no header change. A\n * webhook's accepted responses carry no headers in the IR, so `diffWebhooks`\n * has nothing of the kind to compare.\n */\nfunction diffResponseHeaders(oldOp: Operation, newOp: Operation): ResponseHeaderChange[] {\n  const oldEntries = contentEntries(oldOp);\n  const newEntries = contentEntries(newOp);\n  const pairs = pairContentEntries(oldEntries, newEntries);\n  const paired = new Set<ContentEntry>();\n  const changes: ResponseHeaderChange[] = [];\n  // Every change says which response entry it is about, in the position\n  // `ResponseContentTypesChange` reports an entry: a status code (a lone\n  // 2xx's `responseStatusCode` included), or the fallback key, or neither\n  // only for a lone 2xx of a hand-built IR that carries no code.\n  const at = (entry: ContentEntry, change: ResponseHeaderChange): ResponseHeaderChange => {\n    const { kind, headerName, ...rest } = change;\n    return { kind, headerName, ...entryLocation(entry), ...rest };\n  };\n  for (const entry of newEntries) {\n    const old = pairs.get(entry);\n    if (!old) continue;\n    paired.add(old);\n    const { pairs: headers, added, removed } = pairResponseHeaders(old.headers, entry.headers);\n    for (const header of added) changes.push(at(entry, classifyResponseHeaderChange('header-added', header.name)));\n    for (const header of removed) changes.push(at(old, classifyResponseHeaderChange('header-removed', header.name)));\n    for (const [before, after] of headers) {\n      for (const change of headerChanges(before, after)) changes.push(at(entry, change));\n    }\n  }\n  for (const old of oldEntries) {\n    if (paired.has(old) || !old.key.startsWith('success:')) continue;\n    for (const header of old.headers)\n      changes.push(at(old, classifyResponseHeaderChange('header-removed', header.name)));\n  }\n  return changes;\n}\n\n/**\n * Where a response entry is, as a change reports it: its status code (a\n * lone 2xx's `responseStatusCode` included), else its fallback key, else\n * nothing — a primary that carries no code, which among the parser's\n * operations is only one declaring no 2xx/3xx, whose primary carries no\n * headers or media types of its own to report.\n */\nfunction entryLocation(entry: ContentEntry): Pick<ResponseHeaderChange, 'statusCode' | 'fallback'> {\n  return {\n    ...(entry.statusCode !== undefined ? { statusCode: entry.statusCode } : {}),\n    ...(entry.fallback !== undefined ? { fallback: entry.fallback } : {}),\n  };\n}\n\n/**\n * What changed about one header both specs declare, in the order\n * `diffParams` reports a parameter's: its spelling, its type, its\n * requiredness, its `deprecated` flag. Each kind is classified from the\n * reader's side by `classifyResponseHeaderChange`; the name is the new\n * spec's spelling.\n */\nfunction headerChanges(before: ResponseHeader, after: ResponseHeader): ResponseHeaderChange[] {\n  const changes: ResponseHeaderChange[] = [];\n  const name = after.name;\n  const respelled = parameterNameShift(before, after);\n  if (respelled) changes.push({ ...classifyResponseHeaderChange('header-name-changed', name), ...respelled });\n  if (!typeRefsEqual(before.type, after.type)) {\n    if (primitivesDifferOnlyByFormat(before.type, after.type)) {\n      changes.push({\n        ...classifyResponseHeaderChange('header-format-changed', name),\n        details: formatChangeDetails(before.type, after.type),\n      });\n    } else {\n      changes.push(classifyResponseHeaderChange('header-type-changed', name));\n    }\n  }\n  if (before.required !== after.required) {\n    changes.push(classifyResponseHeaderChange('header-required-changed', name, after.required));\n  }\n  const deprecation = deprecationFlip(before, after);\n  if (deprecation) {\n    changes.push({\n      ...classifyResponseHeaderChange('header-deprecated-changed', name),\n      ...deprecation,\n      details: deprecationDetails(deprecation.newDeprecated),\n    });\n  }\n  return changes;\n}\n\n/**\n * Per response entry both specs have, the media types the new spec added,\n * removed, retyped or reparameterized. Media types are compared by essence\n * (`pairMediaTypeBodies`), as the parser types them, so a key that only\n * changed case, whitespace or `charset` is the same media type, and each is\n * reported as written in the spec that declares it; a pair whose other\n * parameters differ is reparameterized, which is additive. A retype is a\n * body whose shape changed (`retypedBodies`), left out only when another\n * comparison reports that very body: the entry's own body on both sides,\n * for two primaries (`responseChanged`) or two errors of one code\n * (`errorsChanged`) — never for a primary paired with an alternate 2xx.\n * Entries pair by status code (`pairContentEntries`), a lone 2xx by its\n * `responseStatusCode`; two lone primaries of different codes pair with each\n * other, and only a lone 2xx that carries no code (a hand-built IR) pairs by\n * the media types it offers, else with the other spec's primary. An error\n * only one spec has is not a media-type change — a code that came or went\n * is the errors diff's business — and neither is a 2xx the new spec adds,\n * but a 2xx the old spec declared and the new does not has no other diff to\n * report it, so its media types are reported as removed: the formats\n * callers could ask for under that code are gone.\n */\nfunction diffResponseContentTypes(\n  oldOp: Operation,\n  newOp: Operation,\n  shapes?: DocumentShapes,\n): ResponseContentTypesChange[] {\n  const oldEntries = contentEntries(oldOp);\n  const newEntries = contentEntries(newOp);\n  const pairs = pairContentEntries(oldEntries, newEntries);\n  const paired = new Set<ContentEntry>();\n  const changes: ResponseContentTypesChange[] = [];\n  for (const entry of newEntries) {\n    const old = pairs.get(entry);\n    if (!old) continue;\n    paired.add(old);\n    const { pairs: bodies, added, removed } = pairMediaTypeBodies(old.bodies, entry.bodies, shapes);\n    const retyped = retypedBodies(bodies, old.ownCoveredElsewhere && entry.ownCoveredElsewhere, shapes);\n    const reparameterized = reparameterizedBodies(bodies);\n    if (added.length === 0 && removed.length === 0 && retyped.length === 0 && reparameterized.length === 0) continue;\n    // Located at the new spec's entry, or — when that entry carries no code\n    // and the change only removes, as when an operation lost its only 2xx —\n    // at the old spec's entry, which declared what is gone; as a removed\n    // header is located at the old entry.\n    const onlyRemoves = added.length === 0 && retyped.length === 0 && reparameterized.length === 0;\n    const unlocated = entry.statusCode === undefined && entry.fallback === undefined;\n    changes.push({\n      ...entryLocation(onlyRemoves && unlocated ? old : entry),\n      added: added.map((body) => body.mediaType),\n      removed: removed.map((body) => body.mediaType),\n      retyped: retyped.map(([, after]) => after.mediaType),\n      reparameterized: reparameterized.map(respelling),\n      classification: removed.length > 0 || retyped.length > 0 ? 'breaking' : 'additive',\n    });\n  }\n  // An error or fallback the old spec alone declares is the errors or\n  // fallback diff's business; a 2xx is nobody else's.\n  for (const old of oldEntries) {\n    if (paired.has(old) || !old.key.startsWith('success:') || old.bodies.length === 0) continue;\n    changes.push({\n      statusCode: old.statusCode,\n      added: [],\n      removed: old.bodies.map((body) => body.mediaType),\n      retyped: [],\n      reparameterized: [],\n      classification: 'breaking',\n    });\n  }\n  return changes;\n}\n\n/**\n * Which old entry each new entry is compared with. Entries pair by key — a\n * status code, a lone 2xx's `responseStatusCode` included — so a lone `201`\n * pairs with the other spec's `201` whether that spec declares it alone or\n * beside a `200` it added, and the added `200` pairs with nothing. When\n * neither primary has a counterpart by code and both carry one, the primary\n * moved (a lone `201` became a lone `200`): the two primaries pair, and\n * `responseStatusCodeChanged` reports the move once rather than every header\n * and media type as removed under one code and added under the other. Only\n * a primary that carries no code (keyed `primary`: an operation declaring no\n * 2xx/3xx at all, whose `response` is `unknown`, or a hand-built IR's lone\n * 2xx) falls back to shape: it pairs with the 2xx entry of the other side\n * that offers the very same media types, whatever that entry's code — the\n * response it most plausibly still is — and, when none does, with the other\n * side's primary; so an operation that lost its only 2xx pairs that entry\n * with its new, empty primary, and `diffResponseHeaders` and\n * `diffResponseContentTypes` report what it declared under its old code. A\n * new entry nothing pairs with is left out of the map.\n */\nfunction pairContentEntries(oldEntries: ContentEntry[], newEntries: ContentEntry[]): Map<ContentEntry, ContentEntry> {\n  const before = new Map(oldEntries.map((entry) => [entry.key, entry]));\n  const pairs = new Map<ContentEntry, ContentEntry>();\n  for (const entry of newEntries) {\n    const old = before.get(entry.key);\n    if (old) pairs.set(entry, old);\n  }\n  const oldPrimary = oldEntries.find((entry) => entry.isPrimary);\n  const newPrimary = newEntries.find((entry) => entry.isPrimary);\n  if (!oldPrimary || !newPrimary || pairs.has(newPrimary)) return pairs;\n  // The old primary is some new entry's by code (a lone `201` beside a new\n  // `200`): the new primary is a 2xx the new spec adds, paired with nothing.\n  if (new Set(pairs.values()).has(oldPrimary)) return pairs;\n  if (oldPrimary.statusCode !== undefined && newPrimary.statusCode !== undefined) {\n    pairs.set(newPrimary, oldPrimary);\n  } else if (newPrimary.statusCode === undefined) {\n    pairs.set(newPrimary, survivingEntry(newPrimary, oldEntries) ?? oldPrimary);\n  } else {\n    pairs.set(survivingEntry(oldPrimary, newEntries) ?? newPrimary, oldPrimary);\n  }\n  return pairs;\n}\n\n/**\n * The 2xx entry among `others` that offers exactly `lone`'s media types,\n * order aside: one spelled the same way first, else one that offers them by\n * essence (`Text/HTML` + `application/pdf` still offers `application/pdf` +\n * `text/html`) — the primary among those, if any. The shape fallback\n * `pairContentEntries` uses for a lone 2xx that carries no\n * `responseStatusCode`.\n */\nfunction survivingEntry(lone: ContentEntry, others: ContentEntry[]): ContentEntry | undefined {\n  const candidates = others.filter((entry) => entry.isPrimary || entry.key.startsWith('success:'));\n  // The entry spelled exactly as the lone one is the response it still is,\n  // before any that only matches by essence: a `200` added beside an\n  // unchanged `201` with `application/yaml; version=2` where the `201` has\n  // `application/yaml` must not take the `201`'s place.\n  const exact = candidates.filter((entry) => signature(entry, 'mediaType') === signature(lone, 'mediaType'));\n  const byEssence = candidates.filter((entry) => signature(entry, 'essence') === signature(lone, 'essence'));\n  const sameMediaTypes = exact.length > 0 ? exact : byEssence;\n  return sameMediaTypes.find((entry) => entry.isPrimary) ?? sameMediaTypes[0];\n}\n\n/** An entry's media types as a multiset of their spellings or of their essences, order aside. */\nfunction signature(entry: ContentEntry, by: 'mediaType' | 'essence'): string {\n  return JSON.stringify(entry.bodies.map((body) => body[by]).sort());\n}\n\nfunction requestBodiesEqual(a: Operation['requestBody'], b: Operation['requestBody']): boolean {\n  if (!a && !b) return true;\n  if (!a || !b) return false;\n  return typeRefsEqual(a, b);\n}\n\nfunction classifyErrorsChange(\n  oldErrors: ErrorResponse[],\n  newErrors: ErrorResponse[],\n): 'none' | 'additive' | 'breaking' {\n  return classifyKeyedResponsesChange(\n    new Map(oldErrors.map((e) => [e.statusCode, e])),\n    new Map(newErrors.map((e) => [e.statusCode, e])),\n  );\n}\n\n/**\n * The fallback responses, keyed the way the spec keys them (`default`,\n * `4XX`), classified like `errors`: one added is additive (the SDK gains a\n * typed fallback), one removed or retyped is breaking.\n */\nfunction classifyFallbackResponsesChange(oldOp: Operation, newOp: Operation): 'none' | 'additive' | 'breaking' {\n  const byKey = (op: Operation): Map<string, { type?: TypeRef }> => {\n    const entries = new Map<string, { type?: TypeRef }>();\n    if (op.defaultResponse) entries.set('default', op.defaultResponse);\n    for (const range of op.rangeResponses ?? []) entries.set(range.range, range);\n    return entries;\n  };\n  return classifyKeyedResponsesChange(byKey(oldOp), byKey(newOp));\n}\n\n/**\n * Responses matched by key (a status code, `default`, a range): a new key is\n * additive (the SDK gains an error class or typed fallback), a removed key is\n * breaking (it loses one), and a shared key whose body type changed is\n * breaking. A key with no body on either side is unchanged.\n */\nfunction classifyKeyedResponsesChange<K>(\n  oldByKey: Map<K, { type?: TypeRef }>,\n  newByKey: Map<K, { type?: TypeRef }>,\n): 'none' | 'additive' | 'breaking' {\n  let hasAdditive = false;\n  let hasBreaking = false;\n\n  for (const key of newByKey.keys()) {\n    if (!oldByKey.has(key)) hasAdditive = true;\n  }\n\n  for (const key of oldByKey.keys()) {\n    if (!newByKey.has(key)) hasBreaking = true;\n  }\n\n  for (const [key, newEntry] of newByKey) {\n    const oldEntry = oldByKey.get(key);\n    if (!oldEntry) continue;\n    if (!oldEntry.type && !newEntry.type) continue;\n    if (!oldEntry.type || !newEntry.type || !typeRefsEqual(oldEntry.type, newEntry.type)) {\n      hasBreaking = true;\n    }\n  }\n\n  if (hasBreaking) return 'breaking';\n  if (hasAdditive) return 'additive';\n  return 'none';\n}\n\n/**\n * Diff an operation's parameters in every location it carries them — path,\n * query, header and cookie, through `locatedParams` — matched by location\n * and name (`paramKey`, which folds a header's name, so `X-Pet-Token` on\n * one side and `x-pet-token` on the other are one parameter, compared like\n * any other and reported as `param-name-changed` rather than as a removal\n * beside an addition — #295) and classified from the caller's side by\n * `classifyParamChange`. Cookie parameters were left out of this walk until\n * #294, so a change to one came out as no change.\n */\nfunction diffParams(oldOp: Operation, newOp: Operation): ParamChange[] {\n  const changes: ParamChange[] = [];\n  const oldByKey = new Map(locatedParams(oldOp).map((e) => [paramKey(e.loc, e.p.name), e]));\n  const newByKey = new Map(locatedParams(newOp).map((e) => [paramKey(e.loc, e.p.name), e]));\n  // Every entry says where its parameter lives, since the name alone no\n  // longer identifies it.\n  const at = (change: ParamChange, loc: ParamLocation): ParamChange => {\n    change.paramLocation = loc;\n    return change;\n  };\n\n  for (const [key, entry] of newByKey) {\n    if (!oldByKey.has(key)) {\n      changes.push(at(classifyParamChange('param-added', entry.p.name, entry.p.required), entry.loc));\n    }\n  }\n\n  for (const [key, entry] of oldByKey) {\n    if (!newByKey.has(key)) {\n      changes.push(at(classifyParamChange('param-removed', entry.p.name), entry.loc));\n    }\n  }\n\n  for (const [key, newEntry] of newByKey) {\n    const oldEntry = oldByKey.get(key);\n    if (!oldEntry) continue;\n    const name = newEntry.p.name;\n    const loc = newEntry.loc;\n\n    const renamed = parameterNameShift(oldEntry.p, newEntry.p);\n    if (renamed) {\n      changes.push({ ...at(classifyParamChange('param-name-changed', name), loc), ...renamed });\n    }\n\n    if (!typeRefsEqual(oldEntry.p.type, newEntry.p.type)) {\n      if (primitivesDifferOnlyByFormat(oldEntry.p.type, newEntry.p.type)) {\n        const change = at(classifyParamChange('param-format-changed', name), loc);\n        change.details = formatChangeDetails(oldEntry.p.type, newEntry.p.type);\n        changes.push(change);\n      } else {\n        changes.push(at(classifyParamChange('param-type-changed', name), loc));\n      }\n    }\n\n    // The media type the value is serialized in (`Parameter.contentType`)\n    // moved: between `schema` and `content`, or between two essences.\n    const reencoded = parameterContentTypeShift(oldEntry.p, newEntry.p);\n    if (reencoded) {\n      changes.push({ ...at(classifyParamChange('param-content-type-changed', name), loc), ...reencoded });\n    }\n\n    if (oldEntry.p.required !== newEntry.p.required) {\n      changes.push(at(classifyParamChange('param-required-changed', name, newEntry.p.required), loc));\n    }\n\n    const oldDefault = serializeDefault(oldEntry.p.default);\n    const newDefault = serializeDefault(newEntry.p.default);\n    if (oldDefault !== newDefault) {\n      const change = at(classifyParamChange('param-default-changed', name), loc);\n      change.oldDefault = oldDefault;\n      change.newDefault = newDefault;\n      change.details = `default ${oldDefault ?? '<unset>'} → ${newDefault ?? '<unset>'}`;\n      changes.push(change);\n    }\n\n    const deprecation = deprecationFlip(oldEntry.p, newEntry.p);\n    if (deprecation) {\n      changes.push({\n        ...at(classifyParamChange('param-deprecated-changed', name), loc),\n        ...deprecation,\n        details: deprecationDetails(deprecation.newDeprecated),\n      });\n    }\n  }\n\n  return changes;\n}\n\nfunction serializeDefault(value: unknown): string | null {\n  if (value === undefined) return null;\n  if (value === null) return 'null';\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  // Objects/arrays: stable JSON. Stringification of equal-valued objects is\n  // deterministic enough for this comparison since callers typically pass\n  // primitives; complex defaults are rare.\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n","import type { Service } from '../ir/types.js';\nimport type { Change } from './types.js';\nimport { diffOperations, type DocumentServers } from './operations.js';\nimport type { DocumentSecurity } from './security.js';\nimport type { DocumentShapes } from './shapes.js';\n\n/**\n * `documentServers` — the two documents' `servers` — lets `diffOperations`\n * resolve what each operation is actually served from, `documentSecurity` —\n * their `security` — what its requests must carry, and `shapes` — their\n * named types — whether two paired bodies are one shape whatever their\n * names; `diffSpecs` passes all three, a direct caller may leave any out.\n */\nexport function diffServices(\n  oldServices: Service[],\n  newServices: Service[],\n  documentServers?: DocumentServers,\n  documentSecurity?: DocumentSecurity,\n  shapes?: DocumentShapes,\n): Change[] {\n  const changes: Change[] = [];\n  const oldByName = new Map(oldServices.map((s) => [s.name, s]));\n  const newByName = new Map(newServices.map((s) => [s.name, s]));\n\n  for (const [name] of newByName) {\n    if (!oldByName.has(name)) {\n      changes.push({ kind: 'service-added', name, classification: 'additive' });\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push({ kind: 'service-removed', name, classification: 'breaking' });\n    }\n  }\n\n  for (const [name, newService] of newByName) {\n    const oldService = oldByName.get(name);\n    if (!oldService) continue;\n\n    changes.push(\n      ...diffOperations(name, oldService.operations, newService.operations, documentServers, documentSecurity, shapes),\n    );\n  }\n\n  return changes;\n}\n","import type { Webhook } from '../ir/types.js';\nimport type { Change, ParamChange, RequestBodyContentTypesChange } from './types.js';\nimport { locatedParams, paramKey, parameterContentTypeShift } from './params.js';\nimport {\n  deprecationDetails,\n  deprecationFlip,\n  parameterNameShift,\n  requestBodyEncodingDetails,\n  requestBodyEncodingShift,\n  tagsShift,\n  type RequestBodyEncodingShift,\n} from './classify.js';\nimport { formatChangeDetails, primitivesDifferOnlyByFormat, typeRefsEqual } from './models.js';\nimport { classifySecurityChange, securityShift, type DocumentSecurity } from './security.js';\nimport { diffRequestBodyContentTypes, ownRepresentationKept } from './media-types.js';\nimport type { DocumentShapes } from './shapes.js';\n\n/**\n * Report webhooks added, removed and modified between two specs. A webhook is\n * keyed by `name` + `httpMethod` (one `webhooks` key may declare several\n * methods), so a method change is a removal plus an addition.\n * `documentSecurity` — the two documents' `security` — lets a webhook that\n * declares none of its own be compared on what it inherits; `diffSpecs`\n * passes it, a direct caller may leave it out.\n */\nexport function diffWebhooks(\n  oldWebhooks: Webhook[],\n  newWebhooks: Webhook[],\n  documentSecurity?: DocumentSecurity,\n  shapes?: DocumentShapes,\n): Change[] {\n  const changes: Change[] = [];\n  const key = (webhook: Webhook): string => `${webhook.httpMethod} ${webhook.name}`;\n  const oldByKey = new Map(oldWebhooks.map((w) => [key(w), w]));\n  const newByKey = new Map(newWebhooks.map((w) => [key(w), w]));\n\n  for (const [k, webhook] of newByKey) {\n    if (!oldByKey.has(k)) {\n      changes.push({\n        kind: 'webhook-added',\n        name: webhook.name,\n        httpMethod: webhook.httpMethod,\n        classification: 'additive',\n      });\n    }\n  }\n\n  for (const [k, webhook] of oldByKey) {\n    if (!newByKey.has(k)) {\n      changes.push({\n        kind: 'webhook-removed',\n        name: webhook.name,\n        httpMethod: webhook.httpMethod,\n        classification: 'breaking',\n      });\n    }\n  }\n\n  for (const [k, newWebhook] of newByKey) {\n    const oldWebhook = oldByKey.get(k);\n    if (!oldWebhook) continue;\n\n    const paramChanges = diffWebhookParams(oldWebhook, newWebhook);\n    const body = diffWebhookBody(oldWebhook, newWebhook, shapes);\n    const responses = diffWebhookResponses(oldWebhook, newWebhook);\n    // Additive either way: the handler's signature is unchanged, but a\n    // changelog has to say it, so a flipped flag alone is a change.\n    const deprecation = deprecationFlip(oldWebhook, newWebhook);\n    const deprecatedChanged = deprecation !== undefined;\n    // What the request carries, `webhook.security ?? document security` on\n    // each side, resolved as an operation's is; read from the receiver's\n    // side, so what the sender may now present must still carry what the\n    // handler checked for.\n    const security = securityShift(oldWebhook, newWebhook, documentSecurity);\n    const securityChanged = security !== undefined;\n    const securityBreaking =\n      security !== undefined &&\n      classifySecurityChange(security.oldSecurity, security.newSecurity, 'receiver') === 'breaking';\n    // Additive always, as on an operation.\n    const tags = tagsShift(oldWebhook, newWebhook);\n    const tagsChanged = tags !== undefined;\n    if (\n      paramChanges.length === 0 &&\n      body.changes.length === 0 &&\n      responses.changes.length === 0 &&\n      !deprecatedChanged &&\n      !securityChanged &&\n      !tagsChanged\n    ) {\n      continue;\n    }\n\n    const hasBreaking =\n      body.breaking ||\n      responses.breaking ||\n      securityBreaking ||\n      paramChanges.some((pc) => pc.classification === 'breaking');\n    const details = [...body.changes, ...responses.changes];\n    changes.push({\n      kind: 'webhook-modified',\n      name: newWebhook.name,\n      httpMethod: newWebhook.httpMethod,\n      paramChanges,\n      requestBodyChanged: body.changes.length > 0,\n      ...body.encoding,\n      ...(body.mediaTypes ? { requestBodyContentTypeChange: body.mediaTypes } : {}),\n      responsesChanged: responses.changes.length > 0,\n      deprecatedChanged,\n      ...deprecation,\n      securityChanged,\n      ...security,\n      tagsChanged,\n      ...tags,\n      ...(details.length > 0 ? { details: details.join('; ') } : {}),\n      classification: hasBreaking ? 'breaking' : 'additive',\n    });\n  }\n\n  return changes;\n}\n\n/**\n * Compare what the handler is handed as a body, from the receiver's side:\n *\n * - type changed, gained or lost: breaking — it is the handler's parameter type.\n * - encoding changed: breaking when the representation the sender now uses\n *   — the media type the new payload is read from, with its shape — is not\n *   one the old spec declared with that shape (compared as a retype is,\n *   `sameShape` through `shapes`), so the handler decodes a wire format it\n *   never saw; additive when the old spec already declared it (a media type\n *   dropped beside a kept one). A payload without media-type lists reads as\n *   breaking. Read through `requestBodyEncodingShift`, the function\n *   `diffOperations` reads an operation's body encoding with — so, as on an\n *   operation, compared only while both sides carry a payload: one\n *   appearing or disappearing takes its encoding with it and is `payload\n *   added` / `payload removed` alone — and carried as `encoding` beside the\n *   `details` string so the change can report both sides.\n * - required → optional: breaking — a handler that assumed a body may get none.\n * - optional → required: additive — the body is now always there.\n * - media types changed, both sides declaring a payload: one the sender can\n *   newly use, or whose body changed type, is breaking — the handler must\n *   decode it; one it can no longer use, or one that only changed a\n *   parameter other than `charset`, is additive. Compared by essence as an\n *   operation's are (`diffRequestBodyContentTypes`), and carried structured\n *   as `mediaTypes` beside the `details` strings.\n */\nfunction diffWebhookBody(\n  oldWebhook: Webhook,\n  newWebhook: Webhook,\n  shapes?: DocumentShapes,\n): {\n  changes: string[];\n  breaking: boolean;\n  encoding?: RequestBodyEncodingShift;\n  mediaTypes?: RequestBodyContentTypesChange;\n} {\n  const changes: string[] = [];\n  let breaking = false;\n\n  const oldBody = oldWebhook.requestBody;\n  const newBody = newWebhook.requestBody;\n  const sameType = oldBody && newBody ? typeRefsEqual(oldBody, newBody) : !oldBody && !newBody;\n  if (!sameType) {\n    changes.push(!oldBody ? 'payload added' : !newBody ? 'payload removed' : 'payload type changed');\n    breaking = true;\n  }\n\n  const encoding = requestBodyEncodingShift(oldWebhook, newWebhook);\n  if (encoding) {\n    changes.push(requestBodyEncodingDetails(encoding));\n    // From the receiver's side: what the sender now sends must be a\n    // representation the old handler already decoded. The sides stay in\n    // old → new order, with `shapes`, so the documents are read the right\n    // way round; `side` picks whose body must survive.\n    if (!ownRepresentationKept(oldWebhook, newWebhook, 'receiver', shapes)) breaking = true;\n  }\n\n  const wasRequired = oldWebhook.requestBodyRequired === true;\n  const isRequired = newWebhook.requestBodyRequired === true;\n  if (wasRequired !== isRequired) {\n    changes.push(isRequired ? 'body optional → required' : 'body required → optional');\n    if (!isRequired) breaking = true;\n  }\n\n  const mediaTypes = diffRequestBodyContentTypes(oldWebhook, newWebhook, 'receiver', shapes);\n  if (mediaTypes) {\n    const said = (what: string, list: string[]): string[] =>\n      list.length > 0 ? [`payload media type${list.length > 1 ? 's' : ''} ${list.join(', ')} ${what}`] : [];\n    changes.push(...said('added', mediaTypes.added), ...said('removed', mediaTypes.removed));\n    changes.push(...said('retyped', mediaTypes.retyped));\n    changes.push(...mediaTypes.reparameterized.map(({ from, to }) => `payload media type ${from} → ${to}`));\n    if (mediaTypes.classification === 'breaking') breaking = true;\n  }\n\n  return { changes, breaking, ...(encoding ? { encoding } : {}), ...(mediaTypes ? { mediaTypes } : {}) };\n}\n\n/**\n * Compare the status codes the sender accepts from the receiver. A code no\n * longer accepted is breaking — a handler that keeps returning it now fails\n * the delivery — and a newly accepted one is additive. Descriptions are not\n * compared, as nowhere else in the differ.\n */\nfunction diffWebhookResponses(oldWebhook: Webhook, newWebhook: Webhook): { changes: string[]; breaking: boolean } {\n  const oldCodes = new Set(oldWebhook.responses.map((r) => r.statusCode));\n  const newCodes = new Set(newWebhook.responses.map((r) => r.statusCode));\n  const removed = [...oldCodes].filter((code) => !newCodes.has(code));\n  const added = [...newCodes].filter((code) => !oldCodes.has(code));\n  const changes: string[] = [];\n  if (removed.length > 0) changes.push(`accepted response ${removed.join(', ')} removed`);\n  if (added.length > 0) changes.push(`accepted response ${added.join(', ')} added`);\n  return { changes, breaking: removed.length > 0 };\n}\n\n/**\n * Diff a webhook's parameters in every location it carries them — header,\n * query and cookie, through the `locatedParams` walk an operation's\n * `diffParams` uses too — from the receiver's side, which inverts the\n * request-side rules `classifyParamChange` applies to an operation: the\n * receiver reads these values and never supplies them. Parameters are\n * matched by location and name (`paramKey`, a header's name case-folded),\n * since OpenAPI lets a header and a query parameter share a name, and every\n * change carries its `paramLocation`.\n *\n * - added: additive, required or not — the sender simply starts carrying it.\n * - name changed: only a header's case can (`X-Pet-Signature` →\n *   `x-pet-signature`); additive, as on an operation — the wire reads it\n *   the same (RFC 9110 §5.1).\n * - removed: breaking — handler code that read it has nothing to read.\n * - type changed: breaking; format-only changes are additive, as elsewhere.\n * - optional → required: additive (now always present);\n *   required → optional: breaking (code that assumed presence breaks).\n * - default changed: additive with details, as the receiver sets no defaults;\n *   kept visible because it may still change what the receiver observes.\n * - deprecated flipped: additive either way, as on an operation's parameter —\n *   the value is still carried with the same type and requiredness.\n */\nfunction diffWebhookParams(oldWebhook: Webhook, newWebhook: Webhook): ParamChange[] {\n  const changes: ParamChange[] = [];\n  const oldByKey = new Map(locatedParams(oldWebhook).map((e) => [paramKey(e.loc, e.p.name), e]));\n  const newByKey = new Map(locatedParams(newWebhook).map((e) => [paramKey(e.loc, e.p.name), e]));\n\n  for (const [k, { p, loc }] of newByKey) {\n    if (!oldByKey.has(k)) {\n      changes.push({ kind: 'param-added', paramName: p.name, classification: 'additive', paramLocation: loc });\n    }\n  }\n\n  for (const [k, { p, loc }] of oldByKey) {\n    if (!newByKey.has(k)) {\n      changes.push({ kind: 'param-removed', paramName: p.name, classification: 'breaking', paramLocation: loc });\n    }\n  }\n\n  for (const [k, { p: newParam, loc }] of newByKey) {\n    const oldEntry = oldByKey.get(k);\n    if (!oldEntry) continue;\n    const oldParam = oldEntry.p;\n    const name = newParam.name;\n\n    const renamed = parameterNameShift(oldParam, newParam);\n    if (renamed) {\n      changes.push({\n        kind: 'param-name-changed',\n        paramName: name,\n        classification: 'additive',\n        paramLocation: loc,\n        ...renamed,\n      });\n    }\n\n    if (!typeRefsEqual(oldParam.type, newParam.type)) {\n      if (primitivesDifferOnlyByFormat(oldParam.type, newParam.type)) {\n        changes.push({\n          kind: 'param-format-changed',\n          paramName: name,\n          classification: 'additive',\n          paramLocation: loc,\n          details: formatChangeDetails(oldParam.type, newParam.type),\n        });\n      } else {\n        changes.push({ kind: 'param-type-changed', paramName: name, classification: 'breaking', paramLocation: loc });\n      }\n    }\n\n    // The media type the value is serialized in (`Parameter.contentType`)\n    // moved: the handler decodes the value the sender now encodes another\n    // way, so breaking from the receiver's side too, like a type change.\n    const reencoded = parameterContentTypeShift(oldParam, newParam);\n    if (reencoded) {\n      changes.push({\n        kind: 'param-content-type-changed',\n        paramName: name,\n        classification: 'breaking',\n        paramLocation: loc,\n        ...reencoded,\n      });\n    }\n\n    if (oldParam.required !== newParam.required) {\n      changes.push({\n        kind: 'param-required-changed',\n        paramName: name,\n        classification: newParam.required ? 'additive' : 'breaking',\n        paramLocation: loc,\n        details: newParam.required ? 'optional → required' : 'required → optional',\n      });\n    }\n\n    const oldDefault = serializeDefault(oldParam.default);\n    const newDefault = serializeDefault(newParam.default);\n    if (oldDefault !== newDefault) {\n      changes.push({\n        kind: 'param-default-changed',\n        paramName: name,\n        classification: 'additive',\n        oldDefault,\n        newDefault,\n        paramLocation: loc,\n        details: `default ${oldDefault ?? '<unset>'} → ${newDefault ?? '<unset>'}`,\n      });\n    }\n\n    const deprecation = deprecationFlip(oldParam, newParam);\n    if (deprecation) {\n      changes.push({\n        kind: 'param-deprecated-changed',\n        paramName: name,\n        classification: 'additive',\n        paramLocation: loc,\n        ...deprecation,\n        details: deprecationDetails(deprecation.newDeprecated),\n      });\n    }\n  }\n\n  return changes;\n}\n\nfunction serializeDefault(value: unknown): string | null {\n  if (value === undefined) return null;\n  if (value === null) return 'null';\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n","import type { ApiSpec, Enum, SecurityRequirementSet } from '../ir/types.js';\nimport type {\n  BehaviorChange,\n  Change,\n  DeprecatedChanged,\n  DeprecatedNode,\n  DiffReport,\n  EnumValueChange,\n  ExtensionsChanged,\n  ExtensionsNode,\n  SecurityChanged,\n  SecurityNode,\n} from './types.js';\nimport { deprecationDetails, deprecationFlip, extensionsShift, type ExtensionsShift } from './classify.js';\nimport { buildDirectionIndex } from './direction.js';\nimport { diffModels } from './models.js';\nimport { classifySecurityChange, securityEqual, type DocumentSecurity, type SecuritySide } from './security.js';\nimport { diffServers } from './servers.js';\nimport { diffServices } from './services.js';\nimport { documentTypes, type DocumentShapes } from './shapes.js';\nimport { diffWebhooks } from './webhooks.js';\n\nexport function diffSpecs(oldSpec: ApiSpec, newSpec: ApiSpec): DiffReport {\n  // Both specs seed the index so a model that was request-facing in either one\n  // is still judged as request-facing here.\n  const directions = buildDirectionIndex(oldSpec, newSpec);\n  // The documents' default requirements travel along so an operation or\n  // webhook is judged by what its requests actually carry, not by whether\n  // it declares a list of its own.\n  const documentSecurity: DocumentSecurity = { old: oldSpec.security, new: newSpec.security };\n  // The documents' named types travel along so two paired bodies compare by\n  // shape: a model the parser only renamed is not a retyped media type.\n  const shapes: DocumentShapes = { old: documentTypes(oldSpec), new: documentTypes(newSpec) };\n\n  const changes: Change[] = [\n    // Where the client sends requests comes first: it is the one change that\n    // touches every operation.\n    ...diffServers(oldSpec, newSpec),\n    // Then what every request must carry, by the same reasoning.\n    ...diffDocumentSecurity(oldSpec, newSpec),\n    ...diffModels(oldSpec.models, newSpec.models, directions),\n    ...diffEnums(oldSpec.enums, newSpec.enums),\n    // The documents' servers travel along so an operation is judged by where\n    // it is actually served from, not by whether it carries an override.\n    ...diffServices(\n      oldSpec.services,\n      newSpec.services,\n      { old: oldSpec.servers, new: newSpec.servers },\n      documentSecurity,\n      shapes,\n    ),\n    ...diffWebhooks(oldSpec.webhooks ?? [], newSpec.webhooks ?? [], documentSecurity, shapes),\n  ];\n\n  const behaviorChanges = collectBehaviorChanges(changes);\n\n  return {\n    oldVersion: oldSpec.version,\n    newVersion: newSpec.version,\n    changes,\n    behaviorChanges,\n    summary: { ...summarize(changes), behaviorChanges: behaviorChanges.length },\n  };\n}\n\n/**\n * The document-level `security` compared between the two documents: one\n * `security-changed` change when the lists differ as sets of alternatives,\n * nothing otherwise. `[]` and an undeclared list both mean no authentication\n * and compare equal. Classified from each side that actually reads the\n * default: the caller's when an operation in either document declares no\n * `security` of its own, the receiver's when a webhook does — breaking if\n * any such side breaks. When nothing inherits it, no request reads the\n * default, so the change is additive.\n */\nfunction diffDocumentSecurity(oldSpec: ApiSpec, newSpec: ApiSpec): Change[] {\n  const oldSecurity = oldSpec.security ?? [];\n  const newSecurity = newSpec.security ?? [];\n  if (securityEqual(oldSecurity, newSecurity)) return [];\n  const inherits = (nodes: Array<{ security?: SecurityRequirementSet[] }>): boolean =>\n    nodes.some((node) => node.security === undefined);\n  const operations = (spec: ApiSpec) => spec.services.flatMap((service) => service.operations);\n  const sides: SecuritySide[] = [];\n  if (inherits(operations(oldSpec)) || inherits(operations(newSpec))) sides.push('caller');\n  if (inherits(oldSpec.webhooks ?? []) || inherits(newSpec.webhooks ?? [])) sides.push('receiver');\n  const breaking = sides.some((side) => classifySecurityChange(oldSecurity, newSecurity, side) === 'breaking');\n  return [{ kind: 'security-changed', oldSecurity, newSecurity, classification: breaking ? 'breaking' : 'additive' }];\n}\n\n/**\n * One entry per flag or nested entry in `changes` that a type signature does\n * not show: a parameter default moving, every `deprecated` flip, and every\n * security change. Each change carries `oldDeprecated`/`newDeprecated` or\n * `oldSecurity`/`newSecurity` beside its flag, so this is a single pass over\n * `changes` that never looks a node up in the IR; a security entry's own\n * classification is `classifySecurityChange` on the two carried lists, read\n * from the node's side, except for the document's, which is copied from the\n * change (it may have been read from both sides).\n */\nfunction collectBehaviorChanges(changes: Change[]): BehaviorChange[] {\n  const out: BehaviorChange[] = [];\n  const flipped = (\n    node: DeprecatedNode,\n    change: { oldDeprecated?: boolean; newDeprecated?: boolean },\n  ): DeprecatedChanged => ({\n    kind: 'deprecated-changed',\n    ...node,\n    oldDeprecated: change.oldDeprecated === true,\n    newDeprecated: change.newDeprecated === true,\n    classification: 'additive',\n  });\n  // An extensions change, the two sides copied from the change as the flip's are.\n  const extended = (node: ExtensionsNode, change: ExtensionsShift): ExtensionsChanged => ({\n    kind: 'extensions-changed',\n    ...node,\n    ...(change.oldExtensions ? { oldExtensions: change.oldExtensions } : {}),\n    ...(change.newExtensions ? { newExtensions: change.newExtensions } : {}),\n    classification: 'additive',\n  });\n  const shifted = (\n    node: SecurityNode,\n    change: { oldSecurity?: SecurityRequirementSet[]; newSecurity?: SecurityRequirementSet[] },\n    classification: 'additive' | 'breaking',\n  ): SecurityChanged => ({\n    kind: 'security-changed',\n    ...node,\n    oldSecurity: change.oldSecurity ?? [],\n    newSecurity: change.newSecurity ?? [],\n    classification,\n  });\n  const shiftedOn = (\n    node: SecurityNode,\n    change: { oldSecurity?: SecurityRequirementSet[]; newSecurity?: SecurityRequirementSet[] },\n    side: SecuritySide,\n  ): SecurityChanged =>\n    shifted(node, change, classifySecurityChange(change.oldSecurity ?? [], change.newSecurity ?? [], side));\n\n  for (const c of changes) {\n    if (c.kind === 'security-changed') {\n      out.push(shifted({ node: 'document' }, c, c.classification));\n      continue;\n    }\n\n    if (c.kind === 'model-modified') {\n      if (c.deprecatedChanged) out.push(flipped({ node: 'model', modelName: c.name }, c));\n      if (c.extensionsChanged) out.push(extended({ node: 'model', modelName: c.name }, c));\n      for (const fc of c.fieldChanges) {\n        const field: ExtensionsNode = { node: 'field', modelName: c.name, fieldName: fc.fieldName };\n        if (fc.kind === 'field-deprecated-changed') out.push(flipped(field, fc));\n        else if (fc.kind === 'field-extensions-changed') out.push(extended(field, fc));\n      }\n      continue;\n    }\n\n    if (c.kind === 'enum-modified') {\n      if (c.deprecatedChanged) out.push(flipped({ node: 'enum', enumName: c.name }, c));\n      if (c.extensionsChanged) out.push(extended({ node: 'enum', enumName: c.name }, c));\n      for (const vc of c.valueChanges) {\n        if (vc.kind !== 'value-deprecated-changed') continue;\n        out.push(flipped({ node: 'enum-value', enumName: c.name, valueName: vc.valueName }, vc));\n      }\n      continue;\n    }\n\n    if (c.kind === 'webhook-modified') {\n      // Only the flag is mirrored: a webhook parameter's default is the\n      // sender's concern, not an SDK-method behavior (see `diffWebhookParams`).\n      if (c.deprecatedChanged) out.push(flipped({ node: 'webhook', name: c.name, httpMethod: c.httpMethod }, c));\n      if (c.securityChanged) {\n        out.push(shiftedOn({ node: 'webhook', name: c.name, httpMethod: c.httpMethod }, c, 'receiver'));\n      }\n      for (const pc of c.paramChanges) {\n        if (pc.kind !== 'param-deprecated-changed') continue;\n        out.push(\n          flipped(\n            {\n              node: 'webhook-parameter',\n              name: c.name,\n              httpMethod: c.httpMethod,\n              paramName: pc.paramName,\n              paramLocation: pc.paramLocation ?? 'header',\n            },\n            pc,\n          ),\n        );\n      }\n      continue;\n    }\n\n    if (c.kind !== 'operation-modified') continue;\n    if (c.deprecatedChanged) {\n      out.push(flipped({ node: 'operation', serviceName: c.serviceName, operationName: c.operationName }, c));\n    }\n    if (c.extensionsChanged) {\n      out.push(extended({ node: 'operation', serviceName: c.serviceName, operationName: c.operationName }, c));\n    }\n    // A list envelope's field, which no model carries, named by the\n    // operation it belongs to.\n    for (const fc of c.envelopeFieldChanges ?? []) {\n      if (fc.kind !== 'field-extensions-changed') continue;\n      out.push(\n        extended(\n          {\n            node: 'envelope-field',\n            serviceName: c.serviceName,\n            operationName: c.operationName,\n            fieldName: fc.fieldName,\n          },\n          fc,\n        ),\n      );\n    }\n    if (c.securityChanged) {\n      out.push(\n        shiftedOn({ node: 'operation', serviceName: c.serviceName, operationName: c.operationName }, c, 'caller'),\n      );\n    }\n    for (const pc of c.paramChanges) {\n      if (pc.kind === 'param-default-changed') {\n        out.push({\n          kind: 'param-default-changed',\n          serviceName: c.serviceName,\n          operationName: c.operationName,\n          paramName: pc.paramName,\n          paramLocation: pc.paramLocation ?? 'query',\n          oldDefault: pc.oldDefault ?? null,\n          newDefault: pc.newDefault ?? null,\n          classification: 'breaking',\n        });\n      } else if (pc.kind === 'param-deprecated-changed') {\n        out.push(\n          flipped(\n            {\n              node: 'parameter',\n              serviceName: c.serviceName,\n              operationName: c.operationName,\n              paramName: pc.paramName,\n              paramLocation: pc.paramLocation ?? 'query',\n            },\n            pc,\n          ),\n        );\n      }\n    }\n    // A response header's flip, with the entry it belongs to carried the way\n    // the change carries it (a status code, a fallback key, or neither for a\n    // lone 2xx); only the flag is mirrored, as for a parameter.\n    for (const hc of c.responseHeaderChanges) {\n      if (hc.kind !== 'header-deprecated-changed') continue;\n      out.push(\n        flipped(\n          {\n            node: 'response-header',\n            serviceName: c.serviceName,\n            operationName: c.operationName,\n            headerName: hc.headerName,\n            ...(hc.statusCode !== undefined ? { statusCode: hc.statusCode } : {}),\n            ...(hc.fallback !== undefined ? { fallback: hc.fallback } : {}),\n          },\n          hc,\n        ),\n      );\n    }\n  }\n  return out;\n}\n\nfunction diffEnums(oldEnums: Enum[], newEnums: Enum[]): Change[] {\n  const changes: Change[] = [];\n  const oldByName = new Map(oldEnums.map((e) => [e.name, e]));\n  const newByName = new Map(newEnums.map((e) => [e.name, e]));\n\n  for (const [name] of newByName) {\n    if (!oldByName.has(name)) {\n      changes.push({ kind: 'enum-added', name, classification: 'additive' });\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push({ kind: 'enum-removed', name, classification: 'breaking' });\n    }\n  }\n\n  for (const [name, newEnum] of newByName) {\n    const oldEnum = oldByName.get(name);\n    if (!oldEnum) continue;\n\n    const valueChanges = diffEnumValues(oldEnum, newEnum);\n    // A flipped flag alone is a change: the values are unchanged, but a\n    // changelog has to say it.\n    const deprecation = deprecationFlip(oldEnum, newEnum);\n    // So is a change to the enum's own extensions (`extensionsShift`).\n    const extensions = extensionsShift(oldEnum, newEnum);\n    if (valueChanges.length > 0 || deprecation || extensions) {\n      const hasBreaking = valueChanges.some((vc) => vc.classification === 'breaking');\n      changes.push({\n        kind: 'enum-modified',\n        name,\n        valueChanges,\n        deprecatedChanged: deprecation !== undefined,\n        ...deprecation,\n        ...(extensions ? { extensionsChanged: true, ...extensions } : {}),\n        classification: hasBreaking ? 'breaking' : 'additive',\n      });\n    }\n  }\n\n  return changes;\n}\n\nfunction diffEnumValues(oldEnum: Enum, newEnum: Enum): EnumValueChange[] {\n  const changes: EnumValueChange[] = [];\n  const oldByName = new Map(oldEnum.values.map((v) => [v.name, v]));\n  const newByName = new Map(newEnum.values.map((v) => [v.name, v]));\n\n  for (const [name] of newByName) {\n    if (!oldByName.has(name)) {\n      changes.push({ kind: 'value-added', valueName: name, classification: 'additive' });\n    }\n  }\n\n  for (const [name] of oldByName) {\n    if (!newByName.has(name)) {\n      changes.push({ kind: 'value-removed', valueName: name, classification: 'breaking' });\n    }\n  }\n\n  for (const [name, newVal] of newByName) {\n    const oldVal = oldByName.get(name);\n    if (!oldVal) continue;\n\n    if (oldVal.value !== newVal.value) {\n      changes.push({\n        kind: 'value-changed',\n        valueName: name,\n        classification: 'breaking',\n        details: `value changed from '${oldVal.value}' to '${newVal.value}'`,\n      });\n    }\n\n    const deprecation = deprecationFlip(oldVal, newVal);\n    if (deprecation) {\n      // The value is still accepted and still emitted, so additive either way.\n      changes.push({\n        kind: 'value-deprecated-changed',\n        valueName: name,\n        classification: 'additive',\n        ...deprecation,\n        details: deprecationDetails(deprecation.newDeprecated),\n      });\n    }\n  }\n\n  return changes;\n}\n\nfunction summarize(changes: Change[]) {\n  let added = 0;\n  let removed = 0;\n  let modified = 0;\n  let breaking = 0;\n  let additive = 0;\n\n  for (const c of changes) {\n    if (c.kind.endsWith('-added')) added++;\n    else if (c.kind.endsWith('-removed')) removed++;\n    // `base-url-changed` is a modification of the document root, so every\n    // change lands in exactly one of the three counts.\n    else if (c.kind.endsWith('-modified') || c.kind.endsWith('-changed')) modified++;\n\n    if (c.classification === 'breaking') breaking++;\n    else additive++;\n  }\n\n  return { added, removed, modified, breaking, additive };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,iBAAiB,QAAmE;CAClG,MAAM,WAAW,OAAO;CACxB,MAAM,YAAY,OAAO,aAAa,CAAC;CACvC,MAAM,aAAuB,CAAC;CAC9B,IAAI,MAAM;CACV,IAAI,SAAS;CAEb,KAAK,MAAM,EAAE,MAAM,OAAO,SAAS,iBAAiB,QAAQ,GAAG;EAC7D,OAAO,SAAS,MAAM,QAAQ,KAAK;EAInC,IAAI,OAAO,OAAO,WAAW,IAAI,GAC/B,OAAO,UAAU,KAAK,CAAC;OAClB;GACL,OAAO,SAAS,MAAM,OAAO,GAAG;GAChC,IAAI,CAAC,WAAW,SAAS,IAAI,GAAG,WAAW,KAAK,IAAI;EACtD;EACA,SAAS;CACX;CAEA,OAAO,S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