@contractkit/plugin-csharp 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/codegen-models.ts","../src/naming.ts","../src/codegen-client.ts","../src/codegen-sdk.ts","../src/hoist.ts","../src/runtime.ts","../src/runtime-converters.ts","../src/scaffold.ts"],"sourcesContent":["import { dirname, join, resolve } from 'node:path';\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, writeFileSync } from 'node:fs';\nimport type {\n ContractKitPlugin,\n ContractRootNode,\n ContractTypeNode,\n IncrementalManifest,\n IncrementalOutputFile,\n IncrementalUnit,\n ModelNode,\n OpRootNode,\n ParamSource,\n PluginContext,\n} from '@contractkit/core';\nimport {\n buildModelIndex,\n collectTransitiveModelRefs,\n collectTypeRefs,\n emptyIncrementalManifest,\n hashFingerprint,\n parseIncrementalManifest,\n runIncrementalCodegen,\n serializeIncrementalManifest,\n} from '@contractkit/core';\nimport { generateCSharpModels, resolveModelsWithInput } from './codegen-models.js';\nimport { deriveClientClassName, deriveClientPropertyName, generateCSharpClient, hasPublicOperations } from './codegen-client.js';\nimport { generateSdkCs, type SdkAggregatorClient } from './codegen-sdk.js';\nimport { collectHoistedTypes } from './hoist.js';\nimport { generateRuntimeCs } from './runtime.js';\nimport { generateConvertersCs } from './runtime-converters.js';\nimport { generateCsproj } from './scaffold.js';\nimport { CSHARP_KEYWORDS, deriveCSharpFileBase } from './naming.js';\n\nexport interface CSharpSdkPluginConfig {\n /** Output directory relative to rootDir (default: \"csharp-sdk\") */\n baseDir?: string;\n /** Root namespace for the generated sources, e.g. \"Acme.Sdk\" (default: \"ContractKit.Sdk\") */\n namespace?: string;\n /** Aggregator class name (default: \"Sdk\"). Also the assembly name when scaffolding. */\n sdkName?: string;\n /**\n * Whether to emit client methods for operations marked `internal`. Defaults to `false` —\n * internal ops are omitted so consumers don't pick them up.\n */\n includeInternal?: boolean;\n /** Emit `<SdkName>.csproj` once, as a user-owned file. Never overwritten. */\n scaffold?: boolean;\n}\n\n/**\n * Bumped when the C# codegen output shape changes in a way that should invalidate every per-file\n * fingerprint, so a plugin upgrade forces full regeneration even when no `.ck` file has changed.\n */\nexport const CSHARP_CODEGEN_VERSION = '1';\n\nconst CACHE_MANIFEST_FILENAME = 'csharp-manifest.json';\nconst DEFAULT_BASE_DIR = 'csharp-sdk';\nconst DEFAULT_NAMESPACE = 'ContractKit.Sdk';\nconst DEFAULT_SDK_NAME = 'Sdk';\n\nconst plugin: ContractKitPlugin = {\n name: 'csharp-sdk',\n async generateTargets(inputs, ctx) {\n const config = ctx.options as CSharpSdkPluginConfig;\n await runCSharpCodegen(inputs, ctx, config, ctx.rootDir);\n },\n};\n\nexport default plugin;\n\nexport function createCSharpSdkPlugin(config: CSharpSdkPluginConfig, rootDir: string): ContractKitPlugin {\n return {\n name: 'csharp-sdk',\n async generateTargets(inputs, ctx) {\n await runCSharpCodegen(inputs, ctx, config, rootDir);\n },\n };\n}\n\nconst NAMESPACE_RE = /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*$/;\nconst SDK_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Reject config that would generate C# which cannot compile. These are runtime checks, not just\n * types: config arrives as JSON, so the TypeScript interface constrains programmatic callers only.\n */\nexport function assertValidConfig(config: CSharpSdkPluginConfig): void {\n const { namespace, sdkName } = config;\n if (namespace !== undefined) {\n if (typeof namespace !== 'string' || !NAMESPACE_RE.test(namespace)) {\n throw new Error(\n `plugin-csharp: namespace '${String(namespace)}' is not a valid C# namespace — expected dot-separated identifiers, e.g. 'Acme.Sdk'.`,\n );\n }\n const keyword = namespace.split('.').find(segment => CSHARP_KEYWORDS.has(segment));\n if (keyword) {\n throw new Error(`plugin-csharp: namespace '${namespace}' contains the C# keyword '${keyword}', which cannot appear in a namespace.`);\n }\n }\n if (sdkName !== undefined) {\n if (typeof sdkName !== 'string' || !SDK_NAME_RE.test(sdkName)) {\n throw new Error(`plugin-csharp: sdkName '${String(sdkName)}' is not a valid C# class name.`);\n }\n if (CSHARP_KEYWORDS.has(sdkName)) {\n throw new Error(`plugin-csharp: sdkName '${sdkName}' is a C# keyword.`);\n }\n }\n for (const key of ['includeInternal', 'scaffold'] as const) {\n const value = config[key];\n if (value !== undefined && typeof value !== 'boolean') {\n throw new Error(`plugin-csharp: ${key} must be a boolean — got ${JSON.stringify(value)}.`);\n }\n }\n}\n\n/**\n * Shared orchestration. Builds per-file fingerprints, reuses unchanged outputs from the manifest,\n * regenerates only the affected files, and rewrites the shared runtime and aggregator every run\n * (they are cheap and depend only on the set of public clients).\n *\n * Honors `ctx.cacheEnabled`, so `--force` bypasses the per-file cache.\n */\nasync function runCSharpCodegen(\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n ctx: PluginContext,\n config: CSharpSdkPluginConfig,\n rootDir: string,\n): Promise<void> {\n assertValidConfig(config);\n\n const { contractRoots } = inputs;\n const namespaceName = config.namespace ?? DEFAULT_NAMESPACE;\n const sdkName = config.sdkName ?? DEFAULT_SDK_NAME;\n const outDir = resolve(rootDir, config.baseDir ?? DEFAULT_BASE_DIR);\n const manifestPath = resolve(ctx.cacheDir, CACHE_MANIFEST_FILENAME);\n\n // Every model shares one C# namespace, so a cross-file reference resolves by name and the only\n // cross-file input a models unit has is which names carry an Input variant.\n const allModels: ModelNode[] = contractRoots.flatMap(root => root.models);\n const modelIndex = buildModelIndex(allModels);\n // Resolved once over every model, so the hoisting pass and each file's renderer agree on which\n // names carry an `Input` variant.\n const modelsWithInput = resolveModelsWithInput(allModels, inputs.modelsWithInput);\n const modelsWithInputArray = [...modelsWithInput].sort();\n\n // Names for the anonymous shapes — unions, inline objects, field-level enums, tuples — that C#\n // needs a declaration for. Computed across every file at once: a discriminated union declared in\n // one file makes member records generated in other files implement its interface.\n const hoisted = collectHoistedTypes(contractRoots, {\n modelIndex,\n modelsWithInput,\n warn: (message, file) => ctx.warn?.(message, file),\n });\n\n const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(CSHARP_CODEGEN_VERSION);\n const units: IncrementalUnit[] = [];\n const clients: SdkAggregatorClient[] = [];\n\n for (const root of contractRoots) {\n const relPath = `Models/${deriveCSharpFileBase(root.file)}.cs`;\n const ownNames = new Set(root.models.map(m => m.name));\n const referenced = referencedModelNames(root);\n const relevantInputModels = modelsWithInputArray.filter(name => ownNames.has(name) || referenced.has(name));\n // A base declared in another file contributes its fields to a record generated here, so the\n // fingerprint has to move when that base does.\n const externalBases = [...referenced]\n .filter(name => !ownNames.has(name))\n .sort()\n .map(name => modelIndex.get(name))\n .filter((m): m is ModelNode => m !== undefined);\n\n // Declarations this file owns, and the interfaces its records implement, are both decided by\n // the whole project, so they belong in the fingerprint alongside the file.\n const ownedDeclarations = (hoisted.byFile.get(root.file) ?? []).map(d => ({ kind: d.kind, name: d.name, needsInput: d.needsInput }));\n const declaredMemberships = [...ownNames]\n .sort()\n .map(name => [name, hoisted.memberships.get(name) ?? []] as const)\n .filter(([, unions]) => unions.length > 0);\n\n const fingerprint = hashFingerprint({\n kind: 'models',\n v: CSHARP_CODEGEN_VERSION,\n relPath,\n namespace: namespaceName,\n root,\n externalBases,\n modelsWithInput: relevantInputModels,\n ownedDeclarations,\n declaredMemberships,\n });\n\n units.push({\n key: `models::${relPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: relPath,\n content: generateCSharpModels(root, {\n namespace: namespaceName,\n modelsWithInput,\n modelIndex,\n hoisted,\n warn: message => ctx.warn?.(message, root.file),\n }),\n },\n ],\n });\n }\n\n // ── Per-op-root client files ─────────────────────────────────────────────\n for (const root of inputs.opRoots) {\n if (!hasPublicOperations(root, config.includeInternal)) continue;\n const relPath = `Clients/${deriveClientClassName(root.file)}.cs`;\n clients.push({ className: deriveClientClassName(root.file), propertyName: deriveClientPropertyName(root.file) });\n\n const referenced = referencedOpModels(root, modelIndex);\n const relevantInputModels = modelsWithInputArray.filter(name => referenced.has(name));\n // A client names the models it takes and returns, so the shapes behind those names — and\n // the declarations hoisted out of them — are part of what this file depends on.\n const referencedModels = [...referenced]\n .sort()\n .map(name => modelIndex.get(name))\n .filter((m): m is ModelNode => m !== undefined);\n\n const fingerprint = hashFingerprint({\n kind: 'client',\n v: CSHARP_CODEGEN_VERSION,\n relPath,\n namespace: namespaceName,\n root,\n referencedModels,\n modelsWithInput: relevantInputModels,\n includeInternal: config.includeInternal ?? false,\n });\n\n units.push({\n key: `client::${relPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: relPath,\n content: generateCSharpClient(root, {\n namespace: namespaceName,\n modelsWithInput,\n modelIndex,\n hoisted,\n includeInternal: config.includeInternal,\n warn: message => ctx.warn?.(message, root.file),\n }),\n },\n ],\n });\n }\n\n // The runtime is a constant, and the aggregator depends only on the list of public clients.\n // Both are small enough that rewriting them every run beats a cache entry.\n const globalFiles: IncrementalOutputFile[] = [\n { relativePath: 'Runtime/Converters.cs', content: generateConvertersCs(namespaceName) },\n { relativePath: 'Runtime/SdkRuntime.cs', content: generateRuntimeCs(namespaceName) },\n { relativePath: `${sdkName}.cs`, content: generateSdkCs(namespaceName, sdkName, clients) },\n ];\n\n // `ifAbsent` marks this user-owned: written once, never overwritten, and never removed as an\n // orphan when the generated tree changes around it.\n if (config.scaffold) {\n globalFiles.push({ relativePath: `${sdkName}.csproj`, content: generateCsproj(namespaceName, sdkName), ifAbsent: true });\n }\n\n const result = runIncrementalCodegen({\n codegenVersion: CSHARP_CODEGEN_VERSION,\n prevManifest,\n globalFiles,\n units,\n fileExists: relPath => existsSync(resolve(outDir, relPath)),\n });\n\n deleteStalePaths(outDir, result.deletedPaths);\n\n for (const { relativePath, content, ifAbsent } of result.filesToWrite) {\n ctx.emitFile(resolve(outDir, relativePath), content, ifAbsent ? { ifAbsent: true } : undefined);\n }\n\n writeManifest(manifestPath, result.manifest);\n}\n\n/** Every model name an operations file names, transitively, so the client's inputs are covered. */\nfunction referencedOpModels(root: OpRootNode, modelIndex: Map<string, ModelNode>): Set<string> {\n const seeds: ContractTypeNode[] = [];\n const addParamSource = (source: ParamSource | undefined): void => {\n if (!source) return;\n if (source.kind === 'params') seeds.push(...source.nodes.map(n => n.type));\n else if (source.kind === 'ref') seeds.push({ kind: 'ref', name: source.name });\n else seeds.push(source.node);\n };\n\n for (const route of root.routes) {\n addParamSource(route.params);\n for (const op of route.operations) {\n addParamSource(op.query);\n addParamSource(op.headers);\n for (const body of op.request?.bodies ?? []) seeds.push(body.bodyType);\n for (const response of op.responses) {\n for (const body of response.bodies) seeds.push(body.bodyType);\n for (const header of response.headers ?? []) seeds.push(header.type);\n }\n }\n }\n\n return collectTransitiveModelRefs(seeds, modelIndex);\n}\n\n/** Every model name a contract root references but may not define, including its bases. */\nfunction referencedModelNames(root: ContractRootNode): Set<string> {\n const refs = new Set<string>();\n for (const model of root.models) {\n if (model.type) collectTypeRefs(model.type, refs);\n for (const f of model.fields) collectTypeRefs(f.type, refs);\n if (model.bases) for (const base of model.bases) refs.add(base);\n }\n return refs;\n}\n\n/** Read the previous run's manifest. Returns an empty manifest when missing or unreadable. */\nfunction readManifest(manifestPath: string): IncrementalManifest {\n if (!existsSync(manifestPath)) return emptyIncrementalManifest(CSHARP_CODEGEN_VERSION);\n try {\n return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return emptyIncrementalManifest(CSHARP_CODEGEN_VERSION);\n }\n}\n\n/** Write the manifest. Errors are swallowed so a broken cache never blocks the build. */\nfunction writeManifest(manifestPath: string, manifest: IncrementalManifest): void {\n try {\n mkdirSync(dirname(manifestPath), { recursive: true });\n writeFileSync(manifestPath, serializeIncrementalManifest(manifest), 'utf-8');\n } catch {\n // best-effort\n }\n}\n\n/**\n * Delete paths from the prior manifest that aren't produced this run, then prune the directories\n * they leave empty. The output tree is nested (`Models/`, `Clients/`, `Runtime/`), so a renamed\n * `.ck` file would otherwise leave an empty directory behind.\n */\nfunction deleteStalePaths(outDir: string, relPaths: string[]): void {\n if (relPaths.length === 0) return;\n const removedDirs = new Set<string>();\n for (const rel of relPaths) {\n const abs = resolve(outDir, rel);\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(join(abs, '..'));\n }\n }\n for (const dir of removedDirs) {\n let current = dir;\n while (current.startsWith(outDir) && current !== outDir) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = join(current, '..');\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n","import type { ContractRootNode, ContractTypeNode, FieldDefault, FieldNode, ModelNode, ScalarTypeNode } from '@contractkit/core';\nimport { buildModelIndex, computeModelsWithInput, resolveEffectiveFields, topoSortModels } from '@contractkit/core';\nimport type { HoistedDecl, HoistResult } from './hoist.js';\nimport { quoteCSharpString, safeMemberName, toCSharpEnumMemberName, toCSharpPropertyName, xmlDocLines } from './naming.js';\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\nexport interface CSharpModelCodegenOptions {\n /** Root namespace the SDK is generated into. Models land in `<namespace>.Models`. */\n namespace: string;\n /** Model names that have a distinct `Input` variant, including ones declared in other files. */\n modelsWithInput?: ReadonlySet<string>;\n /**\n * Every model in the project, for flattening bases and intersections. Defaults to an index of\n * this root's own models, which is enough for a single-file project and for unit tests.\n */\n modelIndex?: ReadonlyMap<string, ModelNode>;\n /** Names assigned to anonymous types by {@link collectHoistedTypes}, across the whole project. */\n hoisted?: HoistResult;\n warn?: (message: string) => void;\n}\n\n/**\n * The `using` block every generated models file carries.\n *\n * There is no import tracker, unlike the Kotlin plugin: every type the models can name is in the\n * base class library, so the set is fixed. An unused `using` is not a compiler warning, and pinning\n * the block keeps the output stable and free of the ordering churn a tracker would produce.\n */\nconst MODEL_USINGS = [\n 'using System;',\n 'using System.Collections.Generic;',\n 'using System.Numerics;',\n 'using System.Text.Json;',\n 'using System.Text.Json.Serialization;',\n] as const;\n\n/**\n * Generate the C# models file for one contract root: a `sealed record` per model, plus `<Name>Input`\n * variants, enums, aliases, and the records, interfaces and converters standing in for the unions\n * and anonymous shapes this file owns.\n *\n * Every model in the project shares the single `<namespace>.Models` namespace, so a reference to a\n * model declared in another `.ck` file needs no import and resolves by name alone. That is also what\n * lets an interface declared in one file be implemented by a record generated in another.\n */\nexport function generateCSharpModels(root: ContractRootNode, opts: CSharpModelCodegenOptions): string {\n const modelsWithInput = resolveModelsWithInput(root.models, opts.modelsWithInput);\n const modelIndex = opts.modelIndex ?? buildModelIndex(root.models);\n\n const ctx: RenderContext = {\n namespace: opts.namespace,\n modelsWithInput,\n modelIndex,\n hoisted: opts.hoisted,\n globalAliases: [],\n warn: opts.warn,\n };\n\n const bodies: string[] = [];\n const append = (lines: string[]): void => {\n // A model whose type is a union emits nothing here — the hoisting pass owns the declaration\n // named after it — so the blank separator has to be conditional or it leaves a gap behind.\n if (lines.length === 0) return;\n bodies.push('', ...lines);\n };\n for (const model of topoSortModels(root.models)) append(generateModel(model, ctx));\n for (const decl of opts.hoisted?.byFile.get(root.file) ?? []) append(generateHoisted(decl, ctx));\n\n return renderFile(`${opts.namespace}.Models`, ctx.globalAliases, [...MODEL_USINGS], bodies);\n}\n\n/**\n * The complete set of model names that need a distinct `Input` variant: the ones passed in, plus\n * the transitive closure over `models`.\n *\n * The hoisting pass and the renderer both have to agree on this — a hoisted shape whose Input twin\n * one of them thinks is unnecessary would leave the other referring to a type nobody emitted.\n */\nexport function resolveModelsWithInput(models: readonly ModelNode[], external: ReadonlySet<string> = new Set()): Set<string> {\n const seed = new Set(external);\n return new Set([...seed, ...computeModelsWithInput([...models], seed)]);\n}\n\n// ─── Render context ────────────────────────────────────────────────────────\n\ninterface RenderContext {\n namespace: string;\n modelsWithInput: ReadonlySet<string>;\n modelIndex: ReadonlyMap<string, ModelNode>;\n hoisted?: HoistResult;\n /** `global using` alias lines this file has to emit above its own `using` block. */\n globalAliases: string[];\n /** When set, type names render fully qualified, as a `global using` alias target must be. */\n qualify?: boolean;\n warn?: (message: string) => void;\n}\n\n/** Build a rendering context for a file outside the models namespace, such as a client. */\nexport function createRenderContext(opts: CSharpModelCodegenOptions & { modelsWithInput: ReadonlySet<string> }): RenderContext {\n return {\n namespace: opts.namespace,\n modelsWithInput: opts.modelsWithInput,\n modelIndex: opts.modelIndex ?? new Map(),\n hoisted: opts.hoisted,\n globalAliases: [],\n warn: opts.warn,\n };\n}\n\n/**\n * Assemble a generated C# file: header, nullable context, global aliases, usings, namespace, bodies.\n *\n * `// <auto-generated/>` turns the nullable context off, so `#nullable enable` follows it\n * explicitly. A `global using` alias has to precede every ordinary `using` in its file, which is\n * why the aliases are collected during rendering and emitted here rather than inline.\n */\nexport function renderFile(namespaceName: string, globalAliases: readonly string[], usings: readonly string[], bodies: string[]): string {\n const lines: string[] = ['// <auto-generated/>', '// Generated by @contractkit/plugin-csharp. Do not edit manually.', '#nullable enable', ''];\n if (globalAliases.length > 0) {\n lines.push(...[...globalAliases].sort());\n lines.push('');\n }\n lines.push(...usings);\n lines.push('');\n lines.push(`namespace ${namespaceName};`);\n lines.push(...bodies);\n lines.push('');\n return lines.join('\\n');\n}\n\n// ─── Type rendering ────────────────────────────────────────────────────────\n\n/**\n * Render a ContractKit type as its C# type expression. Never returns a nullable type unless the type\n * itself is one — the caller appends `?` from the field's own `optional`/`nullable` flags.\n *\n * @param forInput - When true, a reference to a model or hoisted shape with an Input variant renders\n * as `<Name>Input`.\n * @throws {Error} Via the scalar renderer, if a scalar has no C# mapping.\n */\nexport function renderCSharpType(type: ContractTypeNode, ctx: RenderContext, forInput = false): string {\n const decl = ctx.hoisted?.byNode.get(type);\n if (decl) return hoistedTypeName(decl, ctx, forInput);\n\n switch (type.kind) {\n case 'scalar':\n return renderScalar(type.name, ctx);\n case 'literal':\n return literalCSharpType(type.value, ctx);\n case 'array':\n return `${qualify('List', 'System.Collections.Generic.List', ctx)}<${renderCSharpType(type.item, ctx, forInput)}>`;\n case 'record': {\n const key = renderCSharpType(type.key, ctx, forInput);\n const value = renderCSharpType(type.value, ctx, forInput);\n const stringType = qualify('string', 'System.String', ctx);\n if (key !== stringType) {\n ctx.warn?.(\n `A record key of type '${key}' is not representable as a JSON object key; emitting Dictionary<string, ${value}>. ` +\n `Parse the key yourself, or declare the key as a string.`,\n );\n }\n return `${qualify('Dictionary', 'System.Collections.Generic.Dictionary', ctx)}<${stringType}, ${value}>`;\n }\n case 'tuple':\n // Unreachable in the real pipeline: the hoisting pass gives every tuple a record of its\n // own, so the `byNode` lookup above has already returned.\n return jsonElement(ctx);\n case 'ref': {\n const name = forInput && ctx.modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;\n return ctx.qualify ? `${ctx.namespace}.Models.${name}` : name;\n }\n case 'lazy':\n return renderCSharpType(type.inner, ctx, forInput);\n case 'union': {\n // A union with at most one non-null member never gets a declaration: it is either C#'s\n // own nullable type or nothing at all.\n const nonNull = type.members.filter(m => !isNullScalar(m));\n const nullable = nonNull.length !== type.members.length;\n if (nonNull.length === 0) return `${qualify('object', 'System.Object', ctx)}?`;\n if (nonNull.length === 1) {\n const inner = renderCSharpType(nonNull[0]!, ctx, forInput);\n return nullable && !inner.endsWith('?') ? `${inner}?` : inner;\n }\n return jsonElement(ctx);\n }\n case 'enum':\n case 'inlineObject':\n case 'intersection':\n case 'discriminatedUnion':\n // Reached only when the shape could not be given a name — a discriminated union whose\n // tag is not statically known, or a caller that skipped the hoisting pass.\n return jsonElement(ctx);\n }\n}\n\nfunction hoistedTypeName(decl: HoistedDecl, ctx: RenderContext, forInput: boolean): string {\n const bare = forInput && decl.needsInput ? `${decl.name}Input` : decl.name;\n const name = ctx.qualify ? `${ctx.namespace}.Models.${bare}` : bare;\n return decl.nullable ? `${name}?` : name;\n}\n\n/** Pick the short or the fully-qualified spelling, depending on where the type is being written. */\nfunction qualify(short: string, full: string, ctx: RenderContext): string {\n return ctx.qualify ? full : short;\n}\n\nfunction jsonElement(ctx: RenderContext): string {\n return qualify('JsonElement', 'System.Text.Json.JsonElement', ctx);\n}\n\nfunction isNullScalar(type: ContractTypeNode): boolean {\n return type.kind === 'scalar' && type.name === 'null';\n}\n\n/**\n * Map a ContractKit scalar to its C# type.\n *\n * @throws {Error} When a scalar has no mapping, so a scalar added to core fails the build here\n * rather than emitting C# that does not compile.\n */\nexport function renderScalar(name: ScalarTypeNode['name'], ctx: RenderContext): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'interval':\n return qualify('string', 'System.String', ctx);\n case 'number':\n return qualify('double', 'System.Double', ctx);\n // `int` is a JS safe integer in the source language, which overflows C#'s 32-bit int.\n case 'int':\n return qualify('long', 'System.Int64', ctx);\n case 'bigint':\n return qualify('BigInteger', 'System.Numerics.BigInteger', ctx);\n // Carried as a quoted string by DecimalStringConverter, never as a JSON number.\n case 'decimal':\n return qualify('decimal', 'System.Decimal', ctx);\n case 'boolean':\n return qualify('bool', 'System.Boolean', ctx);\n case 'date':\n return qualify('DateOnly', 'System.DateOnly', ctx);\n case 'time':\n return qualify('TimeOnly', 'System.TimeOnly', ctx);\n case 'datetime':\n return qualify('DateTimeOffset', 'System.DateTimeOffset', ctx);\n // Carried as ISO 8601 by IsoTimeSpanConverter, not the BCL's own `d.hh:mm:ss`.\n case 'duration':\n return qualify('TimeSpan', 'System.TimeSpan', ctx);\n case 'uuid':\n return qualify('Guid', 'System.Guid', ctx);\n case 'binary':\n return qualify('byte[]', 'System.Byte[]', ctx);\n case 'null':\n return `${qualify('object', 'System.Object', ctx)}?`;\n case 'unknown':\n case 'json':\n case 'object':\n return jsonElement(ctx);\n default: {\n const _exhaustive: never = name;\n throw new Error(`plugin-csharp: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\nfunction literalCSharpType(value: string | number | boolean, ctx: RenderContext): string {\n if (typeof value === 'string') return qualify('string', 'System.String', ctx);\n if (typeof value === 'boolean') return qualify('bool', 'System.Boolean', ctx);\n return Number.isInteger(value) ? qualify('long', 'System.Int64', ctx) : qualify('double', 'System.Double', ctx);\n}\n\n// ─── Default values ────────────────────────────────────────────────────────\n\nconst MIN_SAFE_BIGINT = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);\n\n/**\n * Whether a `bigint` field's default is written as `new BigInteger(<literal>)` rather than parsed\n * from a string. A number past 2**53 has already lost digits, so it cannot be written as a literal;\n * a bigint keeps the same cutoff so a value renders one way whichever form it arrives in.\n */\nfunction isSafeInteger(value: number | bigint): boolean {\n return typeof value === 'bigint' ? value >= MIN_SAFE_BIGINT && value <= MAX_SAFE_BIGINT : Number.isSafeInteger(value);\n}\n\n/**\n * Render a contract default as a C# expression of the field's own type. Returns `undefined` when the\n * value cannot be expressed, so the field is emitted as `required` rather than with an initializer\n * that will not compile.\n *\n * `memberNames` are the property names of the record the initializer sits in. Inside that record a\n * simple name resolves to a member before a type, so `public Rating? Rating { get; init; } =\n * Rating.Neutral;` reads the instance property and fails with CS0236. C#'s rule that lets a member\n * share its type's name applies only when the member's type is exactly that type, and `Rating?` is\n * `Nullable<Rating>`. An enum a member would shadow is written from the global namespace instead.\n */\nfunction renderDefault(\n value: FieldDefault,\n type: ContractTypeNode,\n ctx: RenderContext,\n memberNames: ReadonlySet<string> = new Set(),\n): string | undefined {\n const enumType = (name: string): string => (memberNames.has(name) ? `global::${ctx.namespace}.Models.${name}` : name);\n\n const inner = type.kind === 'lazy' ? type.inner : type;\n\n if (typeof value === 'boolean') return String(value);\n\n // A `bigint` value comes from a `bigint` field, whose case below writes it from its exact digits.\n if (typeof value === 'number' || typeof value === 'bigint') {\n if (inner.kind === 'scalar') {\n switch (inner.name) {\n case 'int':\n return `${value}L`;\n case 'number':\n return `${value}d`;\n case 'decimal':\n return `${value}m`;\n case 'bigint':\n return isSafeInteger(value) ? `new BigInteger(${value})` : `BigInteger.Parse(\"${value}\")`;\n }\n }\n return Number.isInteger(value) ? `${value}L` : `${value}d`;\n }\n\n // A string default against an enum names one of its members. When the enum was hoisted into a\n // real C# enum, that is expressible; a bare inline enum has no type to qualify.\n if (inner.kind === 'enum') {\n const decl = ctx.hoisted?.byNode.get(inner);\n if (!decl || !inner.values.includes(value)) return undefined;\n return `${enumType(decl.name)}.${enumMemberNames(inner.values).get(value)}`;\n }\n\n // The same default written against a NAMED enum contract — `rating: Rating = \"neutral\"`, where\n // `contract Rating: enum(...)` — arrives here as a ref rather than as the enum node.\n if (inner.kind === 'ref') {\n const target = ctx.modelIndex.get(inner.name);\n const targetType = target?.type?.kind === 'lazy' ? target.type.inner : target?.type;\n if (targetType?.kind !== 'enum' || !targetType.values.includes(value)) return undefined;\n return `${enumType(inner.name)}.${enumMemberNames(targetType.values).get(value)}`;\n }\n\n if (inner.kind === 'scalar') {\n switch (inner.name) {\n case 'decimal':\n return /^-?\\d+(\\.\\d+)?$/.test(value) ? `${value}m` : undefined;\n case 'bigint':\n return /^-?\\d+$/.test(value) ? `BigInteger.Parse(${quoteCSharpString(value)})` : undefined;\n case 'string':\n case 'email':\n case 'url':\n case 'interval':\n return quoteCSharpString(value);\n default:\n // date/uuid/datetime and friends have no literal syntax; leave the field required.\n return undefined;\n }\n }\n return quoteCSharpString(value);\n}\n\n// ─── Wire key casing ───────────────────────────────────────────────────────\n\n/** The key casing a contract's `format(input=)` / `format(output=)` names. */\ntype WireCase = NonNullable<ModelNode['outputCase']>;\n\n/**\n * A field name as it travels, which is not always the name the contract declares it under.\n *\n * The two transforms are spelled exactly as `plugin-typescript` spells them, deliberately: the\n * server parses and emits through that plugin's schemas, so a C# client that disagreed with it about\n * where an underscore goes would be wrong in a way no test in either package could see.\n */\nfunction applyWireCase(name: string, wireCase: WireCase | undefined): string {\n if (!wireCase || wireCase === 'camel') return name;\n if (wireCase === 'snake') return name.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/** A case that actually renames something. `camel` is the identity and is treated as absent. */\nfunction renamingCase(wireCase: WireCase | undefined): WireCase | undefined {\n return wireCase && wireCase !== 'camel' ? wireCase : undefined;\n}\n\n/**\n * Which casing one generated record's keys travel in.\n *\n * A response is decoded through `format(output=)` and a request is encoded through `format(input=)`,\n * so a model split into a read record and an `Input` twin takes one each. A model that is NOT split\n * is one record used in both directions, and a `[JsonPropertyName]` cannot spell two different key\n * sets — so a contract asking for two is reported rather than silently resolved in whichever\n * direction happens to be rendered.\n */\nfunction wireCaseFor(model: ModelNode, forInput: boolean, split: boolean, ctx: RenderContext): WireCase | undefined {\n const input = renamingCase(model.inputCase);\n const output = renamingCase(model.outputCase);\n if (split) return forInput ? input : output;\n if (input && output && input !== output) {\n ctx.warn?.(\n `Contract '${model.name}' sets format(input=${input}) and format(output=${output}), but nothing about it splits into an Input variant, ` +\n `so one C# record carries both directions and can only spell one set of keys. The generated keys follow the output casing; ` +\n `a request built from this record will send the wrong ones.`,\n );\n return output;\n }\n return output ?? input;\n}\n\n/**\n * Whether a type puts an anonymous object under a renamed model.\n *\n * Such an object is hoisted into a record of its own, which is rendered without the owning model's\n * casing — the hoisting pass records no owner to take it from. That is a real gap rather than a\n * decision, so it is reported at the one place the owner is still known.\n */\nfunction containsInlineObject(type: ContractTypeNode | undefined): boolean {\n if (!type) return false;\n switch (type.kind) {\n case 'inlineObject':\n return true;\n case 'lazy':\n return containsInlineObject(type.inner);\n case 'array':\n return containsInlineObject(type.item);\n case 'record':\n return containsInlineObject(type.value);\n case 'tuple':\n return type.items.some(containsInlineObject);\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n return (type.members ?? []).some(containsInlineObject);\n default:\n return false;\n }\n}\n\n/** Report the gap above, once per model rather than once per field. */\nfunction warnUncasedNesting(model: ModelNode, fields: readonly FieldNode[], wireCase: WireCase | undefined, ctx: RenderContext): void {\n if (!wireCase) return;\n if (!fields.some(f => containsInlineObject(f.type)) && !containsInlineObject(model.type)) return;\n ctx.warn?.(\n `Contract '${model.name}' is declared format(${model.outputCase ? 'output' : 'input'}=${wireCase}) and holds an anonymous object. ` +\n `The record hoisted out of that object keeps its declared key names, so its keys will not be ${wireCase}-cased. ` +\n `Name the shape as its own contract to fix it.`,\n );\n}\n\n// ─── Model generation ──────────────────────────────────────────────────────\n\nfunction generateModel(model: ModelNode, ctx: RenderContext): string[] {\n if (model.type) return generateAliasModel(model, ctx);\n\n const effective = effectiveFieldsFor(model, ctx);\n const needsSplit = ctx.modelsWithInput.has(model.name) || effective.some(f => f.visibility !== 'normal');\n\n if (!needsSplit) return generateRecordForModel(model.name, effective, ctx, false, model, false);\n\n const readFields = effective.filter(f => f.visibility !== 'writeonly');\n const inputFields = effective.filter(f => f.visibility !== 'readonly');\n return [\n ...generateRecordForModel(model.name, readFields, ctx, false, model, true),\n '',\n ...generateRecordForModel(`${model.name}Input`, inputFields, ctx, true, model, true),\n ];\n}\n\n/**\n * Bases are flattened rather than expressed as C# inheritance. A record can inherit, but a base's\n * `required` properties would then be re-declared by the override rule the contract language\n * applies, and a sealed leaf is what the serializer wants. `resolveEffectiveFields` applies the same\n * later-wins override rule the inheritance validator enforces.\n */\nfunction effectiveFieldsFor(model: ModelNode, ctx: RenderContext): FieldNode[] {\n if (!model.bases || model.bases.length === 0) return model.fields;\n const { fields, unresolved } = resolveEffectiveFields(model.name, ctx.modelIndex);\n for (const name of unresolved) {\n ctx.warn?.(`Contract '${model.name}' extends '${name}', which is not defined; its fields are missing from the generated record.`);\n }\n return fields;\n}\n\nfunction generateAliasModel(model: ModelNode, ctx: RenderContext): string[] {\n const type = model.type!;\n const inner = type.kind === 'lazy' ? type.inner : type;\n\n // A union alias is emitted by the hoisting pass, which owns the declaration named after it.\n if (ctx.hoisted?.byNode.has(inner)) return [];\n\n if (inner.kind === 'enum') return generateEnum(model.name, inner.values, ctx, model.description, model.deprecated);\n\n // An intersection or inline object at model level names a real shape, so it becomes a record\n // rather than an alias to an opaque JSON object.\n if (inner.kind === 'intersection' || inner.kind === 'inlineObject') {\n const { fields, unresolved } = resolveEffectiveFields(inner, ctx.modelIndex);\n for (const name of unresolved) {\n ctx.warn?.(`Contract '${model.name}' references '${name}', which is not defined; its fields are missing from the generated record.`);\n }\n const needsSplit = ctx.modelsWithInput.has(model.name) || fields.some(f => f.visibility !== 'normal');\n if (!needsSplit) return generateRecordForModel(model.name, fields, ctx, false, model, false);\n return [\n ...generateRecordForModel(\n model.name,\n fields.filter(f => f.visibility !== 'writeonly'),\n ctx,\n false,\n model,\n true,\n ),\n '',\n ...generateRecordForModel(\n `${model.name}Input`,\n fields.filter(f => f.visibility !== 'readonly'),\n ctx,\n true,\n model,\n true,\n ),\n ];\n }\n\n // Everything else is a name for an existing type, which C# spells as a using alias. The target\n // has to be fully qualified: a global alias is resolved without the file's own using block.\n addAlias(model.name, type, ctx, false);\n if (ctx.modelsWithInput.has(model.name)) addAlias(`${model.name}Input`, type, ctx, true);\n return [];\n}\n\n/**\n * Record one `global using X = Y;`. A nullable reference type is illegal as an alias target, so the\n * `?` is dropped and the loss reported rather than emitting a file that does not compile.\n */\nfunction addAlias(name: string, type: ContractTypeNode, ctx: RenderContext, forInput: boolean): void {\n const target = renderCSharpType(type, { ...ctx, qualify: true }, forInput);\n let aliased = target;\n if (aliased.endsWith('?') && !isNullableValueType(type, ctx)) {\n aliased = aliased.slice(0, -1);\n ctx.warn?.(\n `Contract '${name}' aliases a nullable type, which C# cannot express as a using alias; ` +\n `'${name}' is generated as '${aliased}'. Declare the nullability at each use site instead.`,\n );\n }\n ctx.globalAliases.push(`global using ${name} = ${aliased};`);\n}\n\n/** Whether `type` renders as a nullable *value* type, which is a legal alias target. */\nfunction isNullableValueType(type: ContractTypeNode, ctx: RenderContext): boolean {\n const inner = type.kind === 'lazy' ? type.inner : type;\n if (inner.kind !== 'union') return false;\n const nonNull = inner.members.filter(m => !isNullScalar(m));\n if (nonNull.length !== 1) return false;\n return VALUE_TYPES.has(renderCSharpType(nonNull[0]!, { ...ctx, qualify: false }, false));\n}\n\n/** The C# spellings that are value types, so `T?` is `Nullable<T>` rather than a nullable reference. */\nconst VALUE_TYPES: ReadonlySet<string> = new Set([\n 'bool',\n 'byte',\n 'decimal',\n 'double',\n 'long',\n 'BigInteger',\n 'DateOnly',\n 'TimeOnly',\n 'DateTimeOffset',\n 'TimeSpan',\n 'Guid',\n 'JsonElement',\n]);\n\nfunction enumMemberNames(values: string[]): Map<string, string> {\n const out = new Map<string, string>();\n const used = new Set<string>();\n for (const value of values) out.set(value, uniqueName(toCSharpEnumMemberName(value), used));\n return out;\n}\n\n/**\n * A C# enum whose members carry their wire spelling.\n *\n * `JsonStringEnumConverter<T>` plus `[JsonStringEnumMemberName]` is what makes the wire value travel\n * without a converter of the generator's own. Both are framework features, so nothing reflective is\n * generated for an enum.\n */\nfunction generateEnum(name: string, values: string[], ctx: RenderContext, description?: string, deprecated?: boolean): string[] {\n const entries = enumMemberNames(values);\n const lines: string[] = [];\n lines.push(...docLines(description, deprecated, ''));\n lines.push(`[JsonConverter(typeof(JsonStringEnumConverter<${name}>))]`);\n lines.push(`public enum ${name}`);\n lines.push('{');\n values.forEach((value, index) => {\n if (index > 0) lines.push('');\n lines.push(` [JsonStringEnumMemberName(${quoteCSharpString(value)})]`);\n lines.push(` ${entries.get(value)},`);\n });\n lines.push('}');\n // An enum has no fields, so no visibility can differ between reading and writing it.\n if (ctx.modelsWithInput.has(name)) ctx.globalAliases.push(`global using ${name}Input = ${ctx.namespace}.Models.${name};`);\n return lines;\n}\n\n/** The union interfaces a generated record has to declare it implements. */\nfunction supertypesFor(readName: string, ctx: RenderContext, forInput: boolean): string[] {\n const unions = ctx.hoisted?.memberships.get(readName) ?? [];\n return unions.map(union => {\n const decl = ctx.hoisted?.byName.get(union);\n return forInput && decl?.needsInput ? `${union}Input` : union;\n });\n}\n\nfunction generateRecordForModel(\n name: string,\n fields: FieldNode[],\n ctx: RenderContext,\n forInput: boolean,\n model: ModelNode,\n split: boolean,\n): string[] {\n const readName = forInput && name.endsWith('Input') ? name.slice(0, -'Input'.length) : name;\n const wireCase = wireCaseFor(model, forInput, split, ctx);\n // Once per model rather than once per generated record, so a split model does not say it twice.\n if (!forInput) warnUncasedNesting(model, fields, wireCase, ctx);\n return renderRecord(name, fields, ctx, forInput, supertypesFor(readName, ctx, forInput), model.description, model.deprecated, wireCase);\n}\n\nfunction renderRecord(\n name: string,\n fields: FieldNode[],\n ctx: RenderContext,\n forInput: boolean,\n supertypes: string[],\n description?: string,\n deprecated?: boolean,\n wireCase?: WireCase,\n): string[] {\n const lines: string[] = [];\n lines.push(...docLines(description, deprecated, ''));\n const implementsClause = supertypes.length > 0 ? ` : ${supertypes.join(', ')}` : '';\n\n // A contract with no visible fields still has to produce a serializable type.\n if (fields.length === 0) {\n lines.push(`public sealed record ${name}${implementsClause};`);\n return lines;\n }\n\n const memberNames = new Set(fields.map(field => memberName(field, name)));\n lines.push(`public sealed record ${name}${implementsClause}`);\n lines.push('{');\n fields.forEach((field, index) => {\n if (index > 0) lines.push('');\n lines.push(...renderField(field, ctx, forInput, name, memberNames, wireCase));\n });\n lines.push('}');\n return lines;\n}\n\n/**\n * One property.\n *\n * The `optional` and `nullable` flags are kept apart, which the Kotlin plugin cannot do: its\n * `explicitNulls = false` is one global switch, so a required-nullable null is dropped from the\n * payload along with the absent optionals. Here each property says for itself whether a null is\n * written, so `x: T | null` sends `null` and `x?: T` sends nothing.\n *\n * Every property is `required` or carries an initializer, so the record is fully assigned under\n * `#nullable enable` and the generated SDK compiles with warnings as errors. `required` is never\n * combined with `[JsonIgnore]`, which System.Text.Json rejects at run time.\n */\n/** The C# property name a field is emitted under inside `ownerTypeName`. */\nfunction memberName(field: FieldNode, ownerTypeName: string): string {\n return safeMemberName(toCSharpPropertyName(field.name), ownerTypeName);\n}\n\nfunction renderField(\n field: FieldNode,\n ctx: RenderContext,\n forInput: boolean,\n ownerTypeName: string,\n memberNames: ReadonlySet<string>,\n wireCase?: WireCase,\n): string[] {\n const propName = memberName(field, ownerTypeName);\n const wireName = applyWireCase(field.name, wireCase);\n\n let typeStr = renderCSharpType(field.type, ctx, forInput);\n if ((field.optional || field.nullable) && !typeStr.endsWith('?')) typeStr += '?';\n\n let initializer = field.default !== undefined ? renderDefault(field.default, field.type, ctx, memberNames) : undefined;\n // A `literal()` field carries exactly one value, so it defaults to it rather than being asked\n // for at every call site. The property is ordinary, so the value always reaches the wire.\n if (initializer === undefined && !field.optional && !field.nullable) {\n const inner = field.type.kind === 'lazy' ? field.type.inner : field.type;\n if (inner.kind === 'literal') initializer = renderDefault(inner.value, inner, ctx, memberNames);\n }\n\n const isRequired = !field.optional && initializer === undefined;\n\n const lines: string[] = [];\n lines.push(...docLines(field.description, field.deprecated, ' '));\n lines.push(` [JsonPropertyName(${quoteCSharpString(wireName)})]`);\n if (field.optional) lines.push(' [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]');\n const suffix = initializer !== undefined ? ` = ${initializer};` : '';\n lines.push(` public ${isRequired ? 'required ' : ''}${typeStr} ${propName} { get; init; }${suffix}`);\n return lines;\n}\n\n// ─── Hoisted declarations ──────────────────────────────────────────────────\n\n/** Emit the declaration standing in for one anonymous type, plus its Input twin when it needs one. */\nfunction generateHoisted(decl: HoistedDecl, ctx: RenderContext): string[] {\n const read = generateHoistedVariant(decl, ctx, false);\n if (!decl.needsInput) return read;\n return [...read, '', ...generateHoistedVariant(decl, ctx, true)];\n}\n\nfunction generateHoistedVariant(decl: HoistedDecl, ctx: RenderContext, forInput: boolean): string[] {\n const name = forInput ? `${decl.name}Input` : decl.name;\n switch (decl.kind) {\n case 'enum':\n return generateEnum(name, decl.values ?? [], ctx, decl.description);\n case 'record':\n return renderRecord(\n name,\n (decl.fields ?? []).filter(f => (forInput ? f.visibility !== 'readonly' : f.visibility !== 'writeonly')),\n ctx,\n forInput,\n supertypesFor(decl.name, ctx, forInput),\n decl.description,\n );\n case 'tuple':\n return generateTupleRecord(decl, name, ctx, forInput);\n case 'plainUnion':\n return generatePlainUnion(decl, name, ctx, forInput);\n case 'discriminatedUnion':\n return generateDiscriminatedUnion(decl, name, ctx, forInput);\n }\n}\n\n/** `element.Deserialize<T>(options)!`, the read expression a generated converter uses per member. */\nfunction deserializeExpr(type: ContractTypeNode, ctx: RenderContext, forInput: boolean): string {\n return `element.Deserialize<${renderCSharpType(type, ctx, forInput)}>(options)!`;\n}\n\n/**\n * A contract tuple. It travels as a JSON array, which no BCL type does: `ValueTuple` serializes as\n * an object, and a property-level `[JsonConverter]` cannot reach a tuple nested inside a `List<>`.\n * A record with a type-level converter travels correctly wherever the type appears.\n */\nfunction generateTupleRecord(decl: HoistedDecl, name: string, ctx: RenderContext, forInput: boolean): string[] {\n const items = decl.items ?? [];\n const converterName = `${name}Converter`;\n const parameters = items.map((item, index) => `${renderCSharpType(item, ctx, forInput)} Item${index}`).join(', ');\n\n const lines: string[] = [];\n lines.push(...docLines(decl.description, undefined, ''));\n lines.push(`[JsonConverter(typeof(${converterName}))]`);\n lines.push(`public sealed record ${name}(${parameters});`);\n lines.push('');\n lines.push(`/// <summary>Reads and writes <see cref=\"${name}\"/> as a JSON array.</summary>`);\n lines.push(`public sealed class ${converterName} : JsonConverter<${name}>`);\n lines.push('{');\n lines.push(` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' using var document = JsonDocument.ParseValue(ref reader);');\n lines.push(' var array = document.RootElement;');\n lines.push(` if (array.ValueKind != JsonValueKind.Array || array.GetArrayLength() != ${items.length})`);\n lines.push(' {');\n lines.push(` throw new JsonException(\"Expected a JSON array of ${items.length} elements for ${name}.\");`);\n lines.push(' }');\n lines.push('');\n lines.push(` return new ${name}(`);\n items.forEach((item, index) => {\n const expr = `array[${index}].Deserialize<${renderCSharpType(item, ctx, forInput)}>(options)!`;\n lines.push(` ${expr}${index === items.length - 1 ? '' : ','}`);\n });\n lines.push(' );');\n lines.push(' }');\n lines.push('');\n lines.push(` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' writer.WriteStartArray();');\n items.forEach((_, index) => lines.push(` JsonSerializer.Serialize(writer, value.Item${index}, options);`));\n lines.push(' writer.WriteEndArray();');\n lines.push(' }');\n lines.push('}');\n return lines;\n}\n\n/**\n * A plain `union(A | B)` becomes an abstract record with one nested member record per member, so\n * callers get a closed set to switch over instead of an untyped JSON value. The private constructor\n * is what closes it: only the nested records can derive from it.\n *\n * Decoding tries each member in declaration order and takes the first that parses, which is exactly\n * what Zod's `z.union` does on the server. Anything else would let the client and the service\n * disagree about a payload both of them accept.\n */\nfunction generatePlainUnion(decl: HoistedDecl, name: string, ctx: RenderContext, forInput: boolean): string[] {\n const converterName = `${name}Converter`;\n const members = decl.members ?? [];\n\n const lines: string[] = [];\n lines.push(...docLines(decl.description, undefined, ''));\n lines.push(`[JsonConverter(typeof(${converterName}))]`);\n lines.push(`public abstract record ${name}`);\n lines.push('{');\n lines.push(` private ${name}() { }`);\n for (const member of members) {\n lines.push('');\n lines.push(` public sealed record ${member.wrapperName}(${renderCSharpType(member.type, ctx, forInput)} Value) : ${name};`);\n }\n lines.push('}');\n lines.push('');\n lines.push(`/// <summary>Reads <see cref=\"${name}\"/> by trying each member in declaration order.</summary>`);\n lines.push(`public sealed class ${converterName} : JsonConverter<${name}>`);\n lines.push('{');\n lines.push(` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' using var document = JsonDocument.ParseValue(ref reader);');\n lines.push(' var element = document.RootElement;');\n lines.push('');\n for (const member of members) {\n lines.push(' try');\n lines.push(' {');\n lines.push(` return new ${name}.${member.wrapperName}(${deserializeExpr(member.type, ctx, forInput)});`);\n lines.push(' }');\n lines.push(' catch (JsonException)');\n lines.push(' {');\n lines.push(' // Not this member; fall through to the next.');\n lines.push(' }');\n lines.push('');\n }\n lines.push(` throw new JsonException(\"No ${name} member matched the payload.\");`);\n lines.push(' }');\n lines.push('');\n lines.push(` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' switch (value)');\n lines.push(' {');\n for (const member of members) {\n lines.push(` case ${name}.${member.wrapperName} member:`);\n lines.push(' JsonSerializer.Serialize(writer, member.Value, options);');\n lines.push(' break;');\n }\n lines.push(' default:');\n lines.push(` throw new JsonException($\"Unknown ${name} member {value.GetType().Name}.\");`);\n lines.push(' }');\n lines.push(' }');\n lines.push('}');\n return lines;\n}\n\n/**\n * A `discriminated(by=tag, A | B)` becomes an interface its member records implement, with a\n * converter that dispatches on the tag value.\n *\n * An interface rather than an abstract base record: a record has single inheritance, and the\n * hoisting pass allows one contract to belong to several unions. It is also why the tag stays a real\n * property on each member rather than becoming `[JsonPolymorphic]` metadata, which System.Text.Json\n * refuses to pair with a property of the same name.\n */\nfunction generateDiscriminatedUnion(decl: HoistedDecl, name: string, ctx: RenderContext, forInput: boolean): string[] {\n const converterName = `${name}Converter`;\n const members = (decl.members ?? []).map(member => ({ ...member, recordName: memberRecordName(member.typeName, ctx, forInput) }));\n const discriminator = decl.discriminator ?? '';\n\n const lines: string[] = [];\n lines.push(...docLines(decl.description, undefined, ''));\n lines.push(`[JsonConverter(typeof(${converterName}))]`);\n lines.push(`public interface ${name}`);\n lines.push('{');\n lines.push('}');\n lines.push('');\n lines.push(`/// <summary>Reads <see cref=\"${name}\"/> by dispatching on its '${discriminator}' tag.</summary>`);\n lines.push(`public sealed class ${converterName} : JsonConverter<${name}>`);\n lines.push('{');\n lines.push(` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' using var document = JsonDocument.ParseValue(ref reader);');\n lines.push(' var element = document.RootElement;');\n lines.push(\n ` var tag = element.TryGetProperty(${quoteCSharpString(discriminator)}, out var tagElement) && tagElement.ValueKind == JsonValueKind.String`,\n );\n lines.push(' ? tagElement.GetString()');\n lines.push(' : null;');\n lines.push('');\n lines.push(' return tag switch');\n lines.push(' {');\n for (const member of members) {\n lines.push(` ${quoteCSharpString(member.tag ?? '')} => element.Deserialize<${member.recordName}>(options)!,`);\n }\n lines.push(` _ => throw new JsonException($\"Unknown ${name} ${discriminator}: {tag}\"),`);\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n lines.push(` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' switch (value)');\n lines.push(' {');\n for (const member of members) {\n lines.push(` case ${member.recordName} member:`);\n lines.push(' JsonSerializer.Serialize(writer, member, options);');\n lines.push(' break;');\n }\n lines.push(' default:');\n lines.push(` throw new JsonException($\"Unknown ${name} member {value.GetType().Name}.\");`);\n lines.push(' }');\n lines.push(' }');\n lines.push('}');\n return lines;\n}\n\n/** The concrete record name of a union member, in the read or input variant. */\nfunction memberRecordName(typeName: string, ctx: RenderContext, forInput: boolean): string {\n if (!forInput) return typeName;\n const decl = ctx.hoisted?.byName.get(typeName);\n if (decl) return decl.needsInput ? `${typeName}Input` : typeName;\n return ctx.modelsWithInput.has(typeName) ? `${typeName}Input` : typeName;\n}\n\n// ─── Shared helpers ────────────────────────────────────────────────────────\n\n/**\n * XML doc for a declaration. Deprecation is a `<remarks>` line rather than `[Obsolete]`: an obsolete\n * model would raise CS0618 in every generated converter and client that names it, which the\n * compile check treats as an error. Operations, which nothing generated calls, do get `[Obsolete]`.\n */\nfunction docLines(description: string | undefined, deprecated: boolean | undefined, indent: string): string[] {\n const lines: string[] = [];\n if (description) lines.push(...xmlDocLines(description, indent));\n if (deprecated) lines.push(...xmlDocLines('Deprecated in the contract.', indent, 'remarks'));\n return lines;\n}\n\nfunction uniqueName(name: string, used: Set<string>): string {\n if (!used.has(name)) {\n used.add(name);\n return name;\n }\n let n = 2;\n while (used.has(`${name}${n}`)) n++;\n used.add(`${name}${n}`);\n return `${name}${n}`;\n}\n\nexport type { RenderContext };\n","/**\n * Identifier and file-name conversions for C# output.\n *\n * Kept separate from the codegen modules because both the model and the client generators need the\n * same conversions, and a mismatch between them would produce a client that references a property\n * name the model never declared.\n */\n\n/**\n * C#'s reserved keywords — illegal as bare identifiers anywhere, so a name that collides with one\n * has to be escaped with `@`. Contextual keywords (`record`, `required`, `init`, `value`, `var`,\n * `async`, `await`, `yield`, `nameof`, `when`) are legal identifiers and are deliberately absent:\n * escaping them would only make the generated code noisier.\n */\nexport const CSHARP_KEYWORDS: ReadonlySet<string> = new Set([\n 'abstract',\n 'as',\n 'base',\n 'bool',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'checked',\n 'class',\n 'const',\n 'continue',\n 'decimal',\n 'default',\n 'delegate',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'event',\n 'explicit',\n 'extern',\n 'false',\n 'finally',\n 'fixed',\n 'float',\n 'for',\n 'foreach',\n 'goto',\n 'if',\n 'implicit',\n 'in',\n 'int',\n 'interface',\n 'internal',\n 'is',\n 'lock',\n 'long',\n 'namespace',\n 'new',\n 'null',\n 'object',\n 'operator',\n 'out',\n 'override',\n 'params',\n 'private',\n 'protected',\n 'public',\n 'readonly',\n 'ref',\n 'return',\n 'sbyte',\n 'sealed',\n 'short',\n 'sizeof',\n 'stackalloc',\n 'static',\n 'string',\n 'struct',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'uint',\n 'ulong',\n 'unchecked',\n 'unsafe',\n 'ushort',\n 'using',\n 'virtual',\n 'void',\n 'volatile',\n 'while',\n]);\n\n/**\n * Members the C# compiler already declares on a record, plus the ones a record's synthesized\n * members would collide with. A contract field landing on any of these has to be renamed.\n */\nconst RESERVED_MEMBER_NAMES: ReadonlySet<string> = new Set(['Equals', 'GetHashCode', 'GetType', 'ToString', 'EqualityContract', 'PrintMembers']);\n\n/**\n * Prefix `name` with `@` when it is a C# keyword, so it can still be used as a parameter or local.\n * The `@` is a lexical escape only: the identifier is still spelled `name` everywhere it matters,\n * including in `nameof` and in reflection, so nothing downstream has to know about it.\n */\nexport function escapeCSharpIdentifier(name: string): string {\n return CSHARP_KEYWORDS.has(name) ? `@${name}` : name;\n}\n\n/**\n * Convert a contract field name to a C# property name in PascalCase.\n *\n * Separators (`-`, `_`, `.`, spaces) introduce a word boundary and are dropped, so `x-request-id`\n * becomes `XRequestId`. A leading digit gets an underscore prefix, since C# identifiers cannot\n * start with one. No keyword escaping is needed: every C# keyword is lowercase and this always\n * produces an initial capital.\n *\n * The original name is preserved on the wire through `[JsonPropertyName]`, so this conversion is\n * free to be lossy as long as it is deterministic.\n */\nexport function toCSharpPropertyName(name: string): string {\n const words = splitWords(name);\n if (words.length === 0) return '_';\n let result = words.map(capitalize).join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Convert a contract parameter or path placeholder to a C# parameter name in camelCase:\n * `invoice-id` becomes `invoiceId`. Keyword-escaped, because camelCase lands on keywords\n * regularly — a path parameter named `event` or `params` is ordinary in a contract.\n */\nexport function toCSharpParameterName(name: string): string {\n const words = splitWords(name);\n if (words.length === 0) return '_';\n const head = words[0]!.toLowerCase();\n const rest = words.slice(1).map(capitalize);\n let result = head + rest.join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return escapeCSharpIdentifier(result);\n}\n\n/**\n * A C# parameter or local name for each declared name, keyed by that name.\n *\n * Each goes through {@link toCSharpParameterName}, then gains a `_` until it collides with neither\n * one of `taken` nor another name's result, and is keyword-escaped last. The comparison is on the\n * unescaped spelling, since `@class` and `class` are the same identifier to the compiler. Returns\n * the plain conversion in the common case, so existing output stays byte-identical.\n *\n * @param taken Unescaped identifiers the surrounding generated code already binds or reads, which\n * a declared name must not duplicate or shadow.\n */\nexport function bindCSharpParameterNames(names: readonly string[], taken: Iterable<string>): Map<string, string> {\n const unavailable = new Set<string>(taken);\n const bindings = new Map<string, string>();\n for (const name of names) {\n let local = toCSharpParameterName(name).replace(/^@/, '');\n while (unavailable.has(local)) local += '_';\n unavailable.add(local);\n bindings.set(name, escapeCSharpIdentifier(local));\n }\n return bindings;\n}\n\n/**\n * Make a property name safe inside `ownerTypeName`.\n *\n * C# rejects a member whose name matches its enclosing type (CS0542), which a contract hits\n * whenever a model has a field of its own name — `contract Invoice { invoice: ... }`. A record also\n * synthesizes members that a contract field can collide with. Both are resolved by appending\n * `Value`; the wire name is unaffected, since `[JsonPropertyName]` is always emitted.\n */\nexport function safeMemberName(propertyName: string, ownerTypeName: string): string {\n if (propertyName === ownerTypeName || RESERVED_MEMBER_NAMES.has(propertyName)) return `${propertyName}Value`;\n return propertyName;\n}\n\n/**\n * Convert a name to a C# type name in PascalCase. Never escaped: type names are generated (from\n * model names, method names, or status codes) rather than taken verbatim, so a collision with a\n * keyword is a naming bug worth surfacing rather than papering over.\n */\nexport function toCSharpTypeName(name: string): string {\n const words = splitWords(name);\n if (words.length === 0) return '_';\n let result = words.map(capitalize).join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Make an already-composed name safe to use as a C# type name, without re-casing it.\n *\n * Distinct from {@link toCSharpTypeName}, which splits a source name into words and rebuilds it:\n * running that over a name already assembled from PascalCase parts would fold `MV` back to `Mv`.\n */\nexport function sanitizeCSharpTypeName(name: string): string {\n let result = name.replace(/[^a-zA-Z0-9]/g, '');\n if (result.length === 0) return '_';\n result = result.charAt(0).toUpperCase() + result.slice(1);\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Convert an enum member value to a C# enum member name in PascalCase: `in-progress` becomes\n * `InProgress`. The value itself always travels via `[JsonStringEnumMemberName]`, so this only has\n * to be a stable identifier.\n */\nexport function toCSharpEnumMemberName(value: string): string {\n const words = splitWords(value);\n if (words.length === 0) return '_';\n let result = words.map(capitalize).join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Derive the PascalCase base used for a generated file's names from a `.ck` file path:\n * `\"ledger.categories.ck\"` becomes `\"LedgerCategories\"`. Both the models file and the client class\n * for one source file are named from this, so they stay visibly paired in the output tree.\n */\nexport function deriveCSharpFileBase(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op\\.)?ck$/, '') ?? 'models';\n return toCSharpTypeName(base);\n}\n\n/**\n * Render `text` as an XML doc comment indented by `indent`, wrapped in `tag`. Returns `[]` for\n * empty text so callers can splat unconditionally.\n *\n * `///` is a line comment, so unlike Kotlin's KDoc there is no delimiter to break out of. What does\n * have to be handled is XML: an unescaped `&` or `<` in a description makes the doc file malformed,\n * which the compiler reports as a warning and `-warnaserror` turns into a build failure.\n */\nexport function xmlDocLines(text: string, indent: string, tag = 'summary'): string[] {\n if (text.length === 0) return [];\n const safe = escapeXml(text);\n const sourceLines = safe.split('\\n');\n if (sourceLines.length === 1) return [`${indent}/// <${tag}>${sourceLines[0]}</${tag}>`];\n return [`${indent}/// <${tag}>`, ...sourceLines.map(line => `${indent}/// ${line}`.trimEnd()), `${indent}/// </${tag}>`];\n}\n\n/** Escape the three characters that would otherwise make a doc comment malformed XML. */\nexport function escapeXml(text: string): string {\n return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n/**\n * Render `value` as a C# string literal. No `$` handling: interpolated strings are the only place\n * `$` is special, and no generated literal built from contract text is interpolated.\n */\nexport function quoteCSharpString(value: string): string {\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\0/g, '\\\\0');\n return `\"${escaped}\"`;\n}\n\n/**\n * Split an identifier into words on separators and camelCase boundaries.\n * `\"x-request-id\"` becomes `[\"x\", \"request\", \"id\"]`; `\"createdAt\"` becomes `[\"created\", \"At\"]`;\n * `\"myHTTPClient\"` becomes `[\"my\", \"HTTP\", \"Client\"]`.\n */\nfunction splitWords(name: string): string[] {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\n}\n\nfunction capitalize(word: string): string {\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n}\n","import type {\n ModelNode,\n OpOperationNode,\n OpResponseBodyNode,\n OpResponseHeaderNode,\n OpResponseNode,\n OpRootNode,\n OpRouteNode,\n ParamSource,\n} from '@contractkit/core';\nimport { classifyContentType, observableResponses, resolveModifiers } from '@contractkit/core';\nimport type { HoistResult } from './hoist.js';\nimport { createRenderContext, renderCSharpType, renderFile, type RenderContext } from './codegen-models.js';\nimport {\n bindCSharpParameterNames,\n deriveCSharpFileBase,\n quoteCSharpString,\n safeMemberName,\n toCSharpParameterName,\n toCSharpPropertyName,\n toCSharpTypeName,\n xmlDocLines,\n} from './naming.js';\n\nexport interface CSharpClientCodegenOptions {\n namespace: string;\n modelsWithInput: ReadonlySet<string>;\n modelIndex?: ReadonlyMap<string, ModelNode>;\n hoisted?: HoistResult;\n includeInternal?: boolean;\n warn?: (message: string) => void;\n}\n\n/**\n * The `using` block every generated client file carries. Fixed for the same reason the models\n * block is: everything a client can name is in the base class library or in the SDK's own two\n * namespaces.\n */\nfunction clientUsings(namespaceName: string): string[] {\n return [\n 'using System;',\n 'using System.Collections.Generic;',\n 'using System.Globalization;',\n 'using System.Net.Http;',\n 'using System.Numerics;',\n 'using System.Text.Json;',\n 'using System.Text.Json.Serialization;',\n 'using System.Threading;',\n 'using System.Threading.Tasks;',\n 'using System.Xml;',\n `using ${namespaceName}.Models;`,\n `using ${namespaceName}.Runtime;`,\n ];\n}\n\n/** Whether the root has at least one operation eligible for client emission. */\nexport function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;\n }\n }\n return false;\n}\n\nexport function deriveClientClassName(file: string): string {\n return `${deriveCSharpFileBase(file)}Client`;\n}\n\nexport function deriveClientPropertyName(file: string): string {\n return deriveCSharpFileBase(file);\n}\n\n/**\n * Generate the client class for one operations file: one `Task`-returning method per public\n * operation, plus the request and response shapes those methods name.\n */\nexport function generateCSharpClient(root: OpRootNode, opts: CSharpClientCodegenOptions): string {\n const className = deriveClientClassName(root.file);\n const includeInternal = opts.includeInternal ?? false;\n const ctx = createRenderContext(opts);\n\n const publicOps: { route: OpRouteNode; op: OpOperationNode }[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n publicOps.push({ route, op });\n }\n }\n\n // Request and response shapes, emitted after the class: a method's signature names them, and C#\n // does not care about declaration order.\n const shapeLines: string[] = [];\n for (const { route, op } of publicOps) {\n const base = methodBase(deriveMethodName(op, route));\n for (const { source, suffix } of [\n { source: op.query, suffix: 'Query' },\n { source: op.headers, suffix: 'Headers' },\n ]) {\n if (source?.kind !== 'params' || source.nodes.length === 0) continue;\n const shapeName = `${base}${suffix}`;\n shapeLines.push('');\n shapeLines.push(\n ...xmlDocLines(`The ${suffix === 'Query' ? 'query parameters' : 'request headers'} declared on ${where(route, op)}.`, ''),\n );\n shapeLines.push(`public sealed record ${shapeName}`);\n shapeLines.push('{');\n source.nodes.forEach((node, index) => {\n if (index > 0) shapeLines.push('');\n const propName = safeMemberName(toCSharpPropertyName(node.name), shapeName);\n let type = renderCSharpType(node.type, ctx, true);\n const optional = Boolean(node.optional) || node.default !== undefined;\n if (optional && !type.endsWith('?')) type += '?';\n shapeLines.push(` [JsonPropertyName(${quoteCSharpString(node.name)})]`);\n if (optional) shapeLines.push(' [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]');\n shapeLines.push(` public ${optional ? '' : 'required '}${type} ${propName} { get; init; }`);\n });\n shapeLines.push('}');\n }\n shapeLines.push(...responseDeclarations(route, op, ctx));\n }\n\n const methodLines: string[] = [];\n const seen = new Map<string, string>();\n for (const { route, op } of publicOps) {\n const methodName = deriveMethodName(op, route);\n const clash = seen.get(methodName);\n if (clash) {\n throw new Error(\n `plugin-csharp: ${where(route, op)} and ${clash} both generate the client method '${methodName}' on ${className}. ` +\n `Give one of them a distinct 'sdk:' name.`,\n );\n }\n seen.set(methodName, where(route, op));\n methodLines.push('');\n methodLines.push(...generateMethod(route, op, ctx, methodName));\n }\n\n const body: string[] = [];\n body.push('');\n // The basename, not `root.file`: that is an absolute path on whoever ran the build, and\n // embedding it would make the generated source differ between machines.\n body.push(...xmlDocLines(`Operations declared in <c>${root.file.split('/').pop()}</c>.`, ''));\n body.push(`public sealed class ${className}(SdkHttp http)`);\n body.push('{');\n // `methodLines` opens with a blank separator between methods; the first one sits against the\n // class header, so it is dropped rather than left as a gap.\n body.push(...methodLines.slice(1).map(l => (l === '' ? '' : ` ${l}`)));\n body.push('}');\n body.push(...shapeLines);\n\n return renderFile(`${opts.namespace}.Clients`, ctx.globalAliases, clientUsings(opts.namespace), body);\n}\n\nfunction where(route: OpRouteNode, op: OpOperationNode): string {\n return `${op.method.toUpperCase()} ${route.path}`;\n}\n\n/** The PascalCase stem generated type names hang off: the method name without its `Async` suffix. */\nfunction methodBase(methodName: string): string {\n return methodName.endsWith('Async') ? methodName.slice(0, -'Async'.length) : methodName;\n}\n\n// ─── Response shape ────────────────────────────────────────────────────────\n\n/**\n * How a method reports what came back, mirroring the TypeScript, Python and Kotlin SDKs.\n *\n * `simple` is the overwhelmingly common case and returns the body itself. The other two exist\n * because the caller cannot otherwise tell which status, or which mime, it received.\n */\ntype ResponseShape =\n | { kind: 'simple'; response?: OpResponseNode }\n | { kind: 'multiMime'; response: OpResponseNode }\n | { kind: 'multiStatus'; responses: OpResponseNode[] };\n\nfunction responseShape(op: OpOperationNode): ResponseShape {\n // `observableResponses` is shared with the router and the other SDKs, so all of them agree on\n // which statuses are values and which are failures.\n const observable = observableResponses(op);\n if (observable.length > 1) return { kind: 'multiStatus', responses: observable };\n const response = observable[0];\n if (response && response.bodies.length > 1) return { kind: 'multiMime', response };\n return { kind: 'simple', response };\n}\n\nfunction observableOf(shape: ResponseShape): OpResponseNode[] {\n if (shape.kind === 'multiStatus') return shape.responses;\n return shape.response ? [shape.response] : [];\n}\n\n// ─── Method generation ─────────────────────────────────────────────────────\n\nfunction generateMethod(route: OpRouteNode, op: OpOperationNode, ctx: RenderContext, methodName: string): string[] {\n const base = methodBase(methodName);\n const shape = responseShape(op);\n const returnType = returnTypeFor(shape, op, base, ctx);\n const observable = observableOf(shape);\n const expectStatuses = observable.filter(r => r.statusCode < 200 || r.statusCode >= 300).map(r => r.statusCode);\n\n const pathBindings = bindPathParams(route);\n const params = buildMethodParams(route, op, ctx, pathBindings);\n // Everything the body can see by name: a response-header pattern variable must not redeclare one.\n const bound = [...METHOD_LOCALS, ...params.map(p => p.name.replace(/^@/, ''))];\n const signature = [...params.map(p => `${p.type} ${p.name}${p.optional ? ' = null' : ''}`), 'CancellationToken cancellationToken = default'].join(\n ', ',\n );\n\n const lines: string[] = [];\n lines.push(...methodDoc(route, op, observable));\n if (resolveModifiers(route, op).includes('deprecated')) lines.push('[Obsolete(\"Deprecated in the contract\")]');\n\n lines.push(`public async ${returnType === 'void' ? 'Task' : `Task<${returnType}>`} ${methodName}(${signature})`);\n lines.push('{');\n\n const callArgs: string[] = [`HttpMethod.${httpMethodConstant(op.method)}`, buildPathExpression(route.path, route.params, pathBindings)];\n if (op.query) callArgs.push('query: http.Params(query)');\n if (op.headers) callArgs.push('headers: http.Params(customHeaders)');\n const content = bodyArgument(op);\n if (content) callArgs.push(content);\n if (expectStatuses.length > 0) callArgs.push(`expectStatuses: new[] { ${expectStatuses.join(', ')} }`);\n callArgs.push('cancellationToken: cancellationToken');\n\n const assignment = returnType === 'void' ? 'await ' : 'var response = await ';\n lines.push(` ${assignment}http.ExecuteAsync(`);\n callArgs.forEach((arg, index) => {\n lines.push(` ${arg}${index === callArgs.length - 1 ? ').ConfigureAwait(false);' : ','}`);\n });\n lines.push(...returnStatements(shape, op, base, ctx, where(route, op), bound));\n lines.push('}');\n return lines;\n}\n\n/** What a method hands back. Declared before the body so the two cannot drift apart. */\nfunction returnTypeFor(shape: ResponseShape, op: OpOperationNode, base: string, ctx: RenderContext): string {\n if (shape.kind !== 'simple') return `${base}Response`;\n const response = shape.response;\n const body = response?.bodies[0];\n const headers = response?.headers ?? [];\n if (!body) return headers.length > 0 ? headersRecordName(op, base) : 'void';\n const dataType = bodyCSharpType(body, ctx);\n // A declared response header changes the return shape: the body alone cannot carry it.\n return headers.length > 0 ? `${base}Result` : dataType;\n}\n\n/** The C# type of one response body. A non-JSON mime ignores the schema, as in every SDK. */\nfunction bodyCSharpType(body: OpResponseBodyNode, ctx: RenderContext): string {\n switch (classifyContentType(body.contentType)) {\n case 'text':\n return 'string';\n case 'binary':\n return 'byte[]';\n default:\n return renderCSharpType(body.bodyType, ctx, false);\n }\n}\n\n/** The expression that reads one body out of the response. */\nfunction bodyReadExpr(body: OpResponseBodyNode, ctx: RenderContext): string {\n switch (classifyContentType(body.contentType)) {\n case 'text':\n return 'response.Text';\n case 'binary':\n return 'response.Bytes';\n default:\n return `http.ReadJson<${renderCSharpType(body.bodyType, ctx, false)}>(response)`;\n }\n}\n\n/** The statements after `ExecuteAsync`, which turn the response into the declared return type. */\nfunction returnStatements(\n shape: ResponseShape,\n op: OpOperationNode,\n base: string,\n ctx: RenderContext,\n place: string,\n bound: readonly string[],\n): string[] {\n if (shape.kind === 'simple') {\n const response = shape.response;\n const body = response?.bodies[0];\n const headers = response?.headers ?? [];\n if (headers.length === 0) return body ? [` return ${bodyReadExpr(body, ctx)};`] : [];\n const lines = readHeaderLines(headers, headersRecordName(op, base), ctx, place, ' ', bound);\n return body ? [...lines, ` return new ${base}Result(${bodyReadExpr(body, ctx)}, headers);`] : [...lines, ' return headers;'];\n }\n\n if (shape.kind === 'multiMime') {\n const headers = shape.response.headers ?? [];\n const lines = headers.length > 0 ? readHeaderLines(headers, headersRecordName(op, base), ctx, place, ' ', bound) : [];\n lines.push(...mimeSwitch(shape.response, base, undefined, ctx, ' ', headers.length > 0));\n return lines;\n }\n\n // The first declared status is the fall-through, so the switch is exhaustive without a branch\n // for a status the service cannot return.\n const [fallback, ...rest] = shape.responses;\n const lines: string[] = [' switch (response.Status)', ' {'];\n for (const response of rest) {\n lines.push(` case ${response.statusCode}:`);\n lines.push(' {');\n lines.push(...statusBranch(response, op, base, response.statusCode, ctx, place, ' ', bound));\n lines.push(' }');\n lines.push('');\n }\n lines.push(' default:');\n lines.push(' {');\n lines.push(...statusBranch(fallback!, op, base, fallback!.statusCode, ctx, place, ' ', bound));\n lines.push(' }');\n lines.push(' }');\n return lines;\n}\n\n/**\n * One switch branch: read this status's headers, then dispatch over its mimes.\n *\n * Every branch is braced. Two branches each declaring `headers` would otherwise collide, since a\n * declaration in a switch section is scoped to the whole switch block rather than to its own case.\n */\nfunction statusBranch(\n response: OpResponseNode,\n op: OpOperationNode,\n base: string,\n statusCode: number,\n ctx: RenderContext,\n place: string,\n indent: string,\n bound: readonly string[],\n): string[] {\n const lines: string[] = [];\n const headers = response.headers ?? [];\n if (headers.length > 0) lines.push(...readHeaderLines(headers, headersRecordName(op, base, statusCode), ctx, place, indent, bound));\n lines.push(...mimeSwitch(response, base, statusCode, ctx, indent, headers.length > 0));\n return lines;\n}\n\n/**\n * Construct the response case, dispatching on the content type when a status declares several\n * mimes. The first declared mime is the fall-through, for the same reason the first status is.\n */\nfunction mimeSwitch(\n response: OpResponseNode,\n base: string,\n statusCode: number | undefined,\n ctx: RenderContext,\n indent: string,\n hasHeaders: boolean,\n): string[] {\n const bodies = response.bodies;\n const construct = (body: OpResponseBodyNode | undefined): string => {\n const args: string[] = [];\n if (body) args.push(bodyReadExpr(body, ctx));\n if (hasHeaders) args.push('headers');\n return `new ${base}Response.${leafRecordName(response, body, statusCode)}(${args.join(', ')})`;\n };\n\n if (bodies.length <= 1) return [`${indent}return ${construct(bodies[0])};`];\n\n const [fallback, ...rest] = bodies;\n const lines: string[] = [`${indent}switch (response.ContentType)`, `${indent}{`];\n for (const body of rest) {\n lines.push(`${indent} case ${quoteCSharpString(body.contentType)}:`);\n lines.push(`${indent} return ${construct(body)};`);\n }\n lines.push(`${indent} default:`);\n lines.push(`${indent} return ${construct(fallback!)};`);\n lines.push(`${indent}}`);\n return lines;\n}\n\n/** The `content:` argument for the request body, if the operation declares one. */\nfunction bodyArgument(op: OpOperationNode): string | undefined {\n // Only the first declared mime is used, matching the Python and Kotlin SDKs: a method has one\n // signature, and the alternatives describe the same payload in a different encoding.\n const body = op.request?.bodies[0];\n if (!body) return undefined;\n const mime = quoteCSharpString(body.contentType);\n switch (classifyContentType(body.contentType)) {\n case 'multipart':\n return 'content: http.MultipartContent(body)';\n case 'urlencoded':\n return 'content: http.FormContent(body)';\n case 'text':\n return `content: http.TextContent(body, ${mime})`;\n case 'binary':\n return `content: http.BinaryContent(body, ${mime})`;\n default:\n return `content: http.JsonContent(body, ${mime})`;\n }\n}\n\n// ─── Response declarations ─────────────────────────────────────────────────\n\n/**\n * The name of a response-headers record: `<Method><Status>Headers` when the status is part of the\n * value, otherwise `<Method>Headers`.\n *\n * The request-headers record claims `<Method>Headers` first, since it is the one a caller builds by\n * name, so an operation that declares both gets `<Method>ResponseHeaders` for its response side.\n * Two records of one name in one namespace is CS0101.\n */\nfunction headersRecordName(op: OpOperationNode, base: string, statusCode?: number): string {\n if (statusCode !== undefined) return `${base}${statusCode}Headers`;\n return declaresRequestHeadersRecord(op) ? `${base}ResponseHeaders` : `${base}Headers`;\n}\n\n/** Whether the operation's `headers:` block gets a generated `<Method>Headers` record. */\nfunction declaresRequestHeadersRecord(op: OpOperationNode): boolean {\n return op.headers?.kind === 'params' && op.headers.nodes.length > 0;\n}\n\n/**\n * The name of one leaf of a method's response union.\n *\n * Leaves are flat rather than nested per status, so a caller switches in one level. A status with\n * several mimes gets one leaf per mime, keeping the mime and the body type it decodes to\n * correlated.\n */\nfunction leafRecordName(response: OpResponseNode, body: OpResponseBodyNode | undefined, statusCode: number | undefined): string {\n const statusPart = statusCode === undefined ? '' : `Status${statusCode}`;\n if (response.bodies.length <= 1 || !body) return statusPart || 'Body';\n return `${statusPart}${toCSharpTypeName(body.contentType.replace(/[+/.]/g, ' '))}`;\n}\n\n/**\n * The `<Method>Headers`, `<Method>Result` and `<Method>Response` declarations a method's return\n * type names. Emitted alongside the client class, since they belong to one method each.\n */\nfunction responseDeclarations(route: OpRouteNode, op: OpOperationNode, ctx: RenderContext): string[] {\n const shape = responseShape(op);\n const base = methodBase(deriveMethodName(op, route));\n const place = where(route, op);\n const lines: string[] = [];\n\n const headerRecord = (headers: OpResponseHeaderNode[], name: string): void => {\n const parameters = headers\n .map(header => {\n const reader = headerReader(header, place);\n const type = header.optional ? `${reader.type}?` : reader.type;\n return `${type} ${safeMemberName(toCSharpPropertyName(header.name), name)}`;\n })\n .join(', ');\n lines.push('');\n lines.push(...xmlDocLines(`Response headers declared on ${place}.`, ''));\n lines.push(`public sealed record ${name}(${parameters});`);\n };\n\n if (shape.kind === 'simple') {\n const response = shape.response;\n const headers = response?.headers ?? [];\n if (headers.length === 0) return lines;\n headerRecord(headers, headersRecordName(op, base));\n const body = response?.bodies[0];\n if (body) {\n lines.push('');\n lines.push(...xmlDocLines(`The body of ${place}, with the response headers the contract declares.`, ''));\n lines.push(`public sealed record ${base}Result(${bodyCSharpType(body, ctx)} Data, ${headersRecordName(op, base)} Headers);`);\n }\n return lines;\n }\n\n const responses = observableOf(shape);\n const withStatus = shape.kind === 'multiStatus';\n for (const response of responses) {\n const headers = response.headers ?? [];\n if (headers.length > 0) headerRecord(headers, headersRecordName(op, base, withStatus ? response.statusCode : undefined));\n }\n\n lines.push('');\n lines.push(\n ...xmlDocLines(\n `What ${place} returned.\\n\\n` +\n (withStatus\n ? 'The operation declares several statuses the service produces, so the status is part of the value.'\n : 'The status declares several content types, so which one arrived is part of the value.'),\n '',\n ),\n );\n lines.push(`public abstract record ${base}Response`);\n lines.push('{');\n lines.push(` private ${base}Response() { }`);\n for (const response of responses) {\n const statusCode = withStatus ? response.statusCode : undefined;\n const headers = response.headers ?? [];\n const bodies = response.bodies.length > 0 ? response.bodies : [undefined];\n for (const body of bodies) {\n const name = leafRecordName(response, body, statusCode);\n const parameters: string[] = [];\n if (body) parameters.push(`${bodyCSharpType(body, ctx)} Data`);\n if (headers.length > 0) parameters.push(`${headersRecordName(op, base, statusCode)} Headers`);\n lines.push('');\n lines.push(` public sealed record ${name}(${parameters.join(', ')}) : ${base}Response;`);\n }\n }\n lines.push('}');\n return lines;\n}\n\n/**\n * The C# type of a response header, and how to turn the raw string into it.\n *\n * Header values arrive as text, so the declared type is what the caller gets and the conversion\n * happens here. The accepted set mirrors the other SDKs; anything else is rejected at build time\n * rather than silently handed back as a string.\n *\n * @throws {Error} When the header's declared type cannot be read from an HTTP header.\n */\nfunction headerReader(header: OpResponseHeaderNode, place: string): { type: string; read: (raw: string) => string } {\n const scalar = header.type.kind === 'scalar' ? header.type.name : undefined;\n switch (scalar) {\n case 'string':\n case 'email':\n case 'url':\n case 'interval':\n case 'unknown':\n return { type: 'string', read: raw => raw };\n case 'number':\n return { type: 'double', read: raw => `double.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'int':\n return { type: 'long', read: raw => `long.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'bigint':\n return { type: 'BigInteger', read: raw => `BigInteger.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'boolean':\n return { type: 'bool', read: raw => `${raw} == \"true\"` };\n case 'uuid':\n return { type: 'Guid', read: raw => `Guid.Parse(${raw})` };\n case 'date':\n return { type: 'DateOnly', read: raw => `DateOnly.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'time':\n return { type: 'TimeOnly', read: raw => `TimeOnly.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'datetime':\n return { type: 'DateTimeOffset', read: raw => `DateTimeOffset.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'duration':\n return { type: 'TimeSpan', read: raw => `XmlConvert.ToTimeSpan(${raw})` };\n default:\n throw new Error(\n `plugin-csharp: response header '${header.name}' on ${place} is declared as ${describeHeaderType(header.type)}, ` +\n `which cannot be read from an HTTP header. Header values arrive as strings — declare it as string, email, url, uuid, ` +\n `date, time, datetime, duration, interval, int, number, boolean or bigint.`,\n );\n }\n}\n\n/** A short, contract-facing description of a header type, for the rejection above. */\nfunction describeHeaderType(type: { kind: string; name?: string }): string {\n if (type.kind === 'scalar') return `the '${type.name}' scalar`;\n if (type.kind === 'ref') return `the contract '${type.name}'`;\n return `${type.kind === 'array' || type.kind === 'inlineObject' ? 'an' : 'a'} ${type.kind}`;\n}\n\n/** The lines that build one response-headers value out of the response. */\nfunction readHeaderLines(\n headers: OpResponseHeaderNode[],\n typeName: string,\n ctx: RenderContext,\n place: string,\n indent: string,\n bound: readonly string[],\n): string[] {\n // Pattern variables share the statement's scope, and the method's: each needs a name nothing\n // else in either binds.\n const locals = bindCSharpParameterNames(\n headers.filter(h => h.optional).map(h => h.name),\n bound,\n );\n const args = headers.map(header => {\n const reader = headerReader(header, place);\n const name = quoteCSharpString(header.name);\n // A required header the service omitted is a broken contract, not a null the caller has to\n // handle; an optional one simply stays absent.\n if (!header.optional) return reader.read(`http.RequireHeader(response, ${name})`);\n const local = locals.get(header.name)!;\n return `response.Header(${name}) is { } ${local} ? ${reader.read(local)} : null`;\n });\n const lines: string[] = [`${indent}var headers = new ${typeName}(`];\n args.forEach((arg, index) => lines.push(`${indent} ${arg}${index === args.length - 1 ? ');' : ','}`));\n return lines;\n}\n\nfunction methodDoc(route: OpRouteNode, op: OpOperationNode, observable: OpResponseNode[]): string[] {\n const lines: string[] = [];\n const parts: string[] = [];\n if (op.name) parts.push(op.name);\n const description = op.description ?? route.description;\n if (description) parts.push(description);\n if (parts.length > 0) lines.push(...xmlDocLines(parts.join('\\n'), ''));\n\n const thrown = op.responses.filter(r => !observable.includes(r)).map(r => r.statusCode);\n if (thrown.length > 0) lines.push(`/// <exception cref=\"SdkException\">On ${thrown.join(', ')}.</exception>`);\n return lines;\n}\n\n/** `System.Net.Http.HttpMethod` spells its verbs as `HttpMethod.Get`, `HttpMethod.Delete`, and so on. */\nfunction httpMethodConstant(method: string): string {\n const lower = method.toLowerCase();\n return lower.charAt(0).toUpperCase() + lower.slice(1);\n}\n\n// ─── Path building ─────────────────────────────────────────────────────────\n\n/**\n * Placeholder names as the `.ck` grammar allows them: `-` and `.` are legal inside one, so a\n * narrower pattern would leave `{payment-id}` in the path and send the braces to the server.\n */\nconst PATH_PLACEHOLDER = /\\{([a-zA-Z_$][a-zA-Z0-9_$.-]*)\\}/g;\n\n/**\n * Render a route path as the `Path(...)` call that builds the URL.\n *\n * Literal segments stay string literals and dynamic ones go through `Segment(...)`, so exactly the\n * values that came from the caller are percent-encoded. `params` says where a value lives: spread\n * across the signature, or behind one `pathParams` argument when the route declares a model.\n */\nexport function buildPathExpression(path: string, params?: ParamSource, bindings?: ReadonlyMap<string, string>): string {\n const args = path\n .split('/')\n .filter(Boolean)\n .map(raw => {\n PATH_PLACEHOLDER.lastIndex = 0;\n const match = PATH_PLACEHOLDER.exec(raw);\n if (!match || match[0] !== raw) return quoteCSharpString(raw);\n const value =\n params && params.kind !== 'params'\n ? `pathParams.${toCSharpPropertyName(match[1]!)}`\n : (bindings?.get(match[1]!) ?? toCSharpParameterName(match[1]!));\n return `http.Segment(${value})`;\n });\n return `http.Path(${args.join(', ')})`;\n}\n\n// ─── Parameters ────────────────────────────────────────────────────────────\n\n/**\n * Identifiers a generated method binds or reads besides its path parameters: the other arguments\n * {@link buildMethodParams} can declare, the trailing `CancellationToken`, the locals the body\n * declares, and the client's own `http` constructor parameter. A path parameter under one of these\n * names would duplicate an argument (CS0100), clash with a local (CS0136), or hide `http`.\n */\nconst METHOD_LOCALS = ['body', 'query', 'customHeaders', 'pathParams', 'cancellationToken', 'response', 'headers', 'http'] as const;\n\n/**\n * The C# parameter name each inline path parameter is spread into the signature under, keyed by its\n * declared name. Keyword-escaped (`@class`), and suffixed when it lands on one of\n * {@link METHOD_LOCALS} (`body_`). Empty when the route has no inline params.\n */\nfunction bindPathParams(route: OpRouteNode): Map<string, string> {\n if (route.params?.kind !== 'params') return new Map();\n return bindCSharpParameterNames(\n route.params.nodes.map(n => n.name),\n METHOD_LOCALS,\n );\n}\n\ninterface MethodParam {\n name: string;\n type: string;\n optional: boolean;\n}\n\n/**\n * The method signature, in the order a caller reads it: path, body, query, headers — but with every\n * required parameter ahead of every optional one.\n *\n * C# rejects a required parameter after an optional one, which Kotlin allows, so the contract's own\n * order cannot always survive. The relative order within each group is kept, and a trailing\n * `CancellationToken` is appended by the caller.\n */\nfunction buildMethodParams(route: OpRouteNode, op: OpOperationNode, ctx: RenderContext, pathBindings: ReadonlyMap<string, string>): MethodParam[] {\n const params: MethodParam[] = [];\n\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const node of route.params.nodes) {\n params.push({ name: pathBindings.get(node.name)!, type: renderCSharpType(node.type, ctx, true), optional: false });\n }\n } else {\n // Not `params`, which is a C# keyword: the argument would have to be written `@params`.\n params.push({ name: 'pathParams', type: renderParamSourceType(route.params, ctx, ''), optional: false });\n }\n }\n\n const body = op.request?.bodies[0];\n if (body) {\n switch (classifyContentType(body.contentType)) {\n case 'multipart':\n // The caller assembles the parts; the declared contract type describes the fields\n // rather than a value the client can send as one object.\n params.push({ name: 'body', type: 'IEnumerable<SdkPart>', optional: false });\n break;\n case 'binary':\n params.push({ name: 'body', type: 'byte[]', optional: false });\n break;\n case 'text':\n params.push({ name: 'body', type: 'string', optional: false });\n break;\n default:\n params.push({ name: 'body', type: renderCSharpType(body.bodyType, ctx, true), optional: false });\n }\n }\n\n const base = methodBase(deriveMethodName(op, route));\n if (op.query) {\n params.push({ name: 'query', type: renderParamSourceType(op.query, ctx, `${base}Query`), optional: allFieldsOptional(op.query) });\n }\n if (op.headers) {\n params.push({\n name: 'customHeaders',\n type: renderParamSourceType(op.headers, ctx, `${base}Headers`),\n optional: allFieldsOptional(op.headers),\n });\n }\n\n const widened = params.map(p => (p.optional && !p.type.endsWith('?') ? { ...p, type: `${p.type}?` } : p));\n return [...widened.filter(p => !p.optional), ...widened.filter(p => p.optional)];\n}\n\n/** Whether every field of a param source may be omitted, making the whole argument optional. */\nfunction allFieldsOptional(source: ParamSource): boolean {\n if (source.kind !== 'params') return true;\n return source.nodes.every(node => Boolean(node.optional) || node.default !== undefined);\n}\n\nfunction renderParamSourceType(source: ParamSource, ctx: RenderContext, generatedName: string): string {\n if (source.kind === 'ref') return renderCSharpType({ kind: 'ref', name: source.name }, ctx, true);\n if (source.kind === 'type') return renderCSharpType(source.node, ctx, true);\n // The record emitted for this method, or a plain map when the block declares nothing.\n return source.nodes.length > 0 ? generatedName : 'IReadOnlyDictionary<string, string>';\n}\n\n// ─── Method naming ─────────────────────────────────────────────────────────\n\n/**\n * The SDK method name, in the same priority order every ContractKit SDK uses: an explicit `sdk:`,\n * then the operation's `name:`, then a name inferred from the verb and path. C# spells it\n * PascalCase with an `Async` suffix, which is what a .NET caller expects of a `Task`-returning\n * method.\n */\nexport function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {\n if (op.sdk) return `${toCSharpTypeName(op.sdk)}Async`;\n if (op.name) return `${toCSharpTypeName(op.name)}Async`;\n return `${inferMethodName(op.method, route.path)}Async`;\n}\n\nfunction inferMethodName(method: string, path: string): string {\n const parts = [toCSharpTypeName(method)];\n for (const segment of path.split('/').filter(Boolean)) {\n if (segment.startsWith('{')) parts.push(`By${toCSharpTypeName(segment.slice(1, -1))}`);\n else parts.push(toCSharpTypeName(segment));\n }\n return parts.join('');\n}\n","import { xmlDocLines } from './naming.js';\n\nexport interface SdkAggregatorClient {\n className: string;\n propertyName: string;\n}\n\n/**\n * Generate the SDK entry point: one property per generated client, all sharing a single\n * [SdkHttp] and therefore a single `HttpClient`.\n *\n * The Python SDK gives each sub-client its own connection pool; that is a bug worth not repeating,\n * since a caller holding one SDK expects one set of connections.\n */\nexport function generateSdkCs(namespaceName: string, sdkName: string, clients: readonly SdkAggregatorClient[]): string {\n const lines: string[] = ['// <auto-generated/>', '// Generated by @contractkit/plugin-csharp. Do not edit manually.', '#nullable enable', ''];\n lines.push('using System;');\n if (clients.length > 0) lines.push(`using ${namespaceName}.Clients;`);\n lines.push(`using ${namespaceName}.Runtime;`);\n lines.push('');\n lines.push(`namespace ${namespaceName};`);\n lines.push('');\n lines.push(\n ...xmlDocLines(\n 'Entry point to the generated SDK.\\n\\n' +\n 'Holds one SdkHttp, shared by every client, so the SDK keeps a single connection pool.\\n' +\n 'Disposing it disposes the underlying HttpClient, unless you supplied your own.',\n '',\n ),\n );\n lines.push(`public sealed class ${sdkName} : IDisposable`);\n lines.push('{');\n lines.push(` public ${sdkName}(SdkOptions options)`);\n lines.push(' {');\n lines.push(' Http = new SdkHttp(options);');\n for (const client of clients) lines.push(` ${client.propertyName} = new ${client.className}(Http);`);\n lines.push(' }');\n lines.push('');\n lines.push(' public SdkHttp Http { get; }');\n for (const client of clients) {\n lines.push('');\n lines.push(` public ${client.className} ${client.propertyName} { get; }`);\n }\n lines.push('');\n lines.push(' public void Dispose()');\n lines.push(' {');\n lines.push(' Http.Dispose();');\n lines.push(' }');\n lines.push('}');\n lines.push('');\n return lines.join('\\n');\n}\n","import type { ContractRootNode, ContractTypeNode, FieldNode, ModelNode } from '@contractkit/core';\nimport { collectTypeRefs, resolveEffectiveFields } from '@contractkit/core';\nimport { sanitizeCSharpTypeName, toCSharpTypeName } from './naming.js';\n\n/**\n * C# needs a name for every shape a caller can hold. The `.ck` language does not: a union, an enum,\n * or an object literal can appear anonymously inside a field. This pass walks every model in the\n * project and assigns each such node a stable C# declaration, so the type renderer can emit a name\n * and the file emitter can emit the declaration behind it.\n *\n * It runs once over all contract roots rather than per file, because a discriminated union declared\n * in one file makes its member records, which may live in any other file, implement its interface.\n */\n\nexport type HoistKind = 'enum' | 'record' | 'plainUnion' | 'discriminatedUnion' | 'tuple';\n\nexport interface HoistedMember {\n /** The C# type of the member: a model name, or a hoisted declaration's name. */\n typeName: string;\n /** Nested record name inside a plain union's abstract record (`OfPayment`). */\n wrapperName?: string;\n /** Discriminator value for a discriminated union member. */\n tag?: string;\n type: ContractTypeNode;\n}\n\nexport interface HoistedDecl {\n kind: HoistKind;\n name: string;\n /** The `.ck` file whose models file carries this declaration. */\n ownerFile: string;\n /** Whether a distinct `<Name>Input` twin has to be emitted alongside it. */\n needsInput: boolean;\n /** Rendered references become `Name?` — the union had a `null` member. */\n nullable?: boolean;\n members?: HoistedMember[];\n discriminator?: string;\n fields?: FieldNode[];\n values?: string[];\n items?: ContractTypeNode[];\n description?: string;\n}\n\nexport interface HoistResult {\n /** The declaration standing in for an anonymous node, keyed by AST node identity. */\n byNode: Map<ContractTypeNode, HoistedDecl>;\n byName: Map<string, HoistedDecl>;\n /** Declarations each `.ck` file's models file has to emit, in collection order. */\n byFile: Map<string, HoistedDecl[]>;\n /** Model record name → the union interfaces it must declare it implements. */\n memberships: Map<string, string[]>;\n}\n\nexport interface HoistOptions {\n modelIndex: ReadonlyMap<string, ModelNode>;\n modelsWithInput: ReadonlySet<string>;\n warn?: (message: string, file: string) => void;\n}\n\n/** Analyse every model in the project and name the anonymous types that need a C# declaration. */\nexport function collectHoistedTypes(roots: readonly ContractRootNode[], opts: HoistOptions): HoistResult {\n const state: State = {\n ...opts,\n byNode: new Map(),\n byName: new Map(),\n byFile: new Map(),\n memberships: new Map(),\n taken: new Set(roots.flatMap(r => r.models.map(m => m.name))),\n };\n\n for (const root of roots) {\n for (const model of root.models) {\n if (model.type) {\n // A model alias occupies a name already, so only a union claims it here: everything\n // else an alias can hold is emitted directly as that model's own declaration.\n walkType(model.type, model.name, root.file, state, true, model.description);\n }\n for (const field of model.fields) {\n walkType(field.type, `${model.name}${toCSharpTypeName(field.name)}`, root.file, state, false, field.description);\n }\n }\n }\n\n return { byNode: state.byNode, byName: state.byName, byFile: state.byFile, memberships: state.memberships };\n}\n\ninterface State extends HoistOptions {\n byNode: Map<ContractTypeNode, HoistedDecl>;\n byName: Map<string, HoistedDecl>;\n byFile: Map<string, HoistedDecl[]>;\n memberships: Map<string, string[]>;\n /** Every name already claimed by a model or an earlier hoist, so a new one cannot collide. */\n taken: Set<string>;\n}\n\n/**\n * Walk one type, hoisting the nodes that need a name and recursing into the rest.\n *\n * @param atAliasRoot - True when the node is a model's own `type`, i.e. it already has a name.\n * Only unions are claimed there; other shapes are emitted by the model generator itself.\n */\nfunction walkType(type: ContractTypeNode, path: string, ownerFile: string, state: State, atAliasRoot: boolean, description?: string): void {\n switch (type.kind) {\n case 'union':\n hoistPlainUnion(type, path, ownerFile, state, atAliasRoot, description);\n return;\n case 'discriminatedUnion':\n hoistDiscriminatedUnion(type, path, ownerFile, state, atAliasRoot, description);\n return;\n case 'enum':\n if (!atAliasRoot) {\n hoist(\n type,\n { kind: 'enum', name: claimFor(path, state, false), ownerFile, needsInput: false, values: type.values, description },\n state,\n );\n }\n return;\n case 'inlineObject':\n if (!atAliasRoot) hoistRecord(type, type.fields, path, ownerFile, state, description);\n else type.fields.forEach(f => walkType(f.type, `${path}${toCSharpTypeName(f.name)}`, ownerFile, state, false, f.description));\n return;\n case 'intersection': {\n if (atAliasRoot) {\n type.members.forEach(m => walkType(m, path, ownerFile, state, true));\n return;\n }\n const { fields } = resolveEffectiveFields(type, state.modelIndex);\n hoistRecord(type, fields, path, ownerFile, state, description);\n return;\n }\n case 'tuple':\n type.items.forEach((item, i) => walkType(item, `${path}Item${i}`, ownerFile, state, false));\n // Every arity is hoisted. `ValueTuple` does not serialize as a JSON array, and a\n // property-level `[JsonConverter]` cannot reach a tuple nested inside a `List<>`. A\n // hoisted record carries a type-level converter, which travels everywhere the type does.\n hoist(\n type,\n {\n kind: 'tuple',\n name: claimFor(path, state, false),\n ownerFile,\n needsInput: type.items.some(t => typeNeedsInput(t, state)),\n items: type.items,\n description,\n },\n state,\n );\n return;\n case 'array':\n walkType(type.item, path, ownerFile, state, false);\n return;\n case 'record':\n walkType(type.value, path, ownerFile, state, false);\n return;\n case 'lazy':\n walkType(type.inner, path, ownerFile, state, atAliasRoot, description);\n return;\n default:\n return;\n }\n}\n\nfunction hoistRecord(node: ContractTypeNode, fields: FieldNode[], path: string, ownerFile: string, state: State, description?: string): void {\n const name = claimFor(path, state, false);\n for (const f of fields) walkType(f.type, `${name}${toCSharpTypeName(f.name)}`, ownerFile, state, false, f.description);\n hoist(\n node,\n {\n kind: 'record',\n name,\n ownerFile,\n needsInput: fields.some(f => f.visibility !== 'normal' || typeNeedsInput(f.type, state)),\n fields,\n description,\n },\n state,\n );\n}\n\n/**\n * A plain union becomes an abstract record with one nested member record per member, so a caller can\n * switch over it. Two shapes are recognised first because C# expresses them natively: a union whose\n * only non-null member is `T` is just `T?`, and a union of string literals is an enum.\n */\nfunction hoistPlainUnion(\n type: ContractTypeNode & { kind: 'union' },\n path: string,\n ownerFile: string,\n state: State,\n atAliasRoot: boolean,\n description?: string,\n): void {\n const nullable = type.members.some(m => m.kind === 'scalar' && m.name === 'null');\n const members = type.members.filter(m => !(m.kind === 'scalar' && m.name === 'null'));\n\n // `union(T, null)` is C#'s own nullable type; an abstract record would only get in the way.\n if (members.length <= 1) {\n if (members[0]) walkType(members[0], path, ownerFile, state, false);\n return;\n }\n\n if (members.every(m => m.kind === 'literal' && typeof m.value === 'string')) {\n const values = members.map(m => String((m as ContractTypeNode & { kind: 'literal' }).value));\n hoist(type, { kind: 'enum', name: claimFor(path, state, atAliasRoot), ownerFile, needsInput: false, nullable, values, description }, state);\n return;\n }\n\n const name = claimFor(path, state, atAliasRoot);\n const used = new Set<string>();\n const hoisted: HoistedMember[] = [];\n for (const member of members) {\n walkType(member, `${name}${toCSharpTypeName(memberLabel(member, state))}`, ownerFile, state, false);\n const typeName = memberTypeName(member, state);\n hoisted.push({ typeName, wrapperName: uniqueIn(`Of${toCSharpTypeName(memberLabel(member, state))}`, used), type: member });\n }\n\n hoist(\n type,\n {\n kind: 'plainUnion',\n name,\n ownerFile,\n needsInput: members.some(m => typeNeedsInput(m, state)),\n nullable,\n members: hoisted,\n description,\n },\n state,\n );\n}\n\n/**\n * A discriminated union becomes an interface its member records implement directly, with a converter\n * that dispatches on the tag. An interface rather than an abstract base: a record has single\n * inheritance, and one contract can belong to several unions. Members must be model refs or inline\n * objects, and the discriminator field must be a `literal` — an `enum` discriminator is legal in the\n * source language but leaves no statically known tag, so the union degrades to a raw JSON value.\n */\nfunction hoistDiscriminatedUnion(\n type: ContractTypeNode & { kind: 'discriminatedUnion' },\n path: string,\n ownerFile: string,\n state: State,\n atAliasRoot: boolean,\n description?: string,\n): void {\n const name = claimFor(path, state, atAliasRoot);\n const members: HoistedMember[] = [];\n\n for (const member of type.members) {\n const { fields } = resolveEffectiveFields(member, state.modelIndex);\n const discriminatorField = fields.find(f => f.name === type.discriminator);\n const tagType = discriminatorField?.type.kind === 'lazy' ? discriminatorField.type.inner : discriminatorField?.type;\n if (!tagType || tagType.kind !== 'literal') {\n state.warn?.(\n `Discriminated union '${name}' has a member whose '${type.discriminator}' is not a literal, so its tag is not known at build time; ` +\n `emitting a raw JSON value instead of an interface.`,\n ownerFile,\n );\n release(name, state, atAliasRoot);\n return;\n }\n\n const tag = String(tagType.value);\n if (member.kind === 'ref') {\n members.push({ typeName: member.name, tag, type: member });\n } else {\n // An inline member has no record of its own yet; name it after the tag it carries.\n const memberPath = `${name}${toCSharpTypeName(tag)}`;\n hoistRecord(member, fields, memberPath, ownerFile, state, undefined);\n const decl = state.byNode.get(member);\n if (!decl) {\n release(name, state, atAliasRoot);\n return;\n }\n members.push({ typeName: decl.name, tag, type: member });\n }\n }\n\n if (members.length === 0) {\n release(name, state, atAliasRoot);\n return;\n }\n\n const decl: HoistedDecl = {\n kind: 'discriminatedUnion',\n name,\n ownerFile,\n needsInput: type.members.some(m => typeNeedsInput(m, state)),\n members,\n discriminator: type.discriminator,\n description,\n };\n hoist(type, decl, state);\n\n // The member records declare the interface, wherever in the project they are generated.\n for (const member of members) {\n const list = state.memberships.get(member.typeName) ?? [];\n if (!list.includes(name)) list.push(name);\n state.memberships.set(member.typeName, list);\n }\n}\n\n/** A short label for a union member, used to name its member record and any nested hoist. */\nfunction memberLabel(type: ContractTypeNode, state: State): string {\n switch (type.kind) {\n case 'ref':\n return type.name;\n case 'scalar':\n return type.name;\n case 'array':\n return `${memberLabel(type.item, state)}List`;\n case 'record':\n return `${memberLabel(type.value, state)}Map`;\n case 'literal':\n return typeof type.value === 'string' ? type.value : String(type.value);\n case 'lazy':\n return memberLabel(type.inner, state);\n default: {\n const decl = state.byNode.get(type);\n return decl ? decl.name : 'Member';\n }\n }\n}\n\n/** The C# type a union member is wrapped around, once any nested hoisting has happened. */\nfunction memberTypeName(type: ContractTypeNode, state: State): string {\n const decl = state.byNode.get(type);\n if (decl) return decl.name;\n if (type.kind === 'ref') return type.name;\n return '';\n}\n\n/**\n * Whether rendering `type` for a request body differs from rendering it for a response, i.e. it\n * reaches a model that has a distinct `Input` variant. Drives whether a hoisted declaration needs\n * an `Input` twin of its own.\n */\nfunction typeNeedsInput(type: ContractTypeNode, state: State): boolean {\n const refs = new Set<string>();\n collectTypeRefs(type, refs);\n if ([...refs].some(r => state.modelsWithInput.has(r))) return true;\n return hasVisibilityField(type);\n}\n\nfunction hasVisibilityField(type: ContractTypeNode): boolean {\n switch (type.kind) {\n case 'inlineObject':\n return type.fields.some(f => f.visibility !== 'normal' || hasVisibilityField(f.type));\n case 'array':\n return hasVisibilityField(type.item);\n case 'record':\n return hasVisibilityField(type.value);\n case 'lazy':\n return hasVisibilityField(type.inner);\n case 'tuple':\n return type.items.some(hasVisibilityField);\n case 'union':\n case 'intersection':\n case 'discriminatedUnion':\n return type.members.some(hasVisibilityField);\n default:\n return false;\n }\n}\n\nfunction hoist(node: ContractTypeNode, decl: HoistedDecl, state: State): void {\n state.byNode.set(node, decl);\n state.byName.set(decl.name, decl);\n const list = state.byFile.get(decl.ownerFile) ?? [];\n list.push(decl);\n state.byFile.set(decl.ownerFile, list);\n}\n\n/**\n * Reserve a C# declaration name, suffixing until it is free. The path arrives already composed\n * from PascalCase parts, so it is only sanitized — re-casing it would fold `MV` back to `Mv`.\n *\n * A union that *is* a model's declared type keeps that model's name: it already owns it, and the\n * model generator emits nothing else under it.\n */\nfunction claimFor(path: string, state: State, atAliasRoot: boolean): string {\n if (atAliasRoot) return path;\n return uniqueIn(sanitizeCSharpTypeName(path), state.taken);\n}\n\n/** Give a reserved name back, for a hoist that turned out not to be expressible. */\nfunction release(name: string, state: State, atAliasRoot: boolean): void {\n if (!atAliasRoot) state.taken.delete(name);\n}\n\nfunction uniqueIn(base: string, taken: Set<string>): string {\n if (!taken.has(base)) {\n taken.add(base);\n return base;\n }\n let n = 2;\n while (taken.has(`${base}${n}`)) n++;\n taken.add(`${base}${n}`);\n return `${base}${n}`;\n}\n","/**\n * The `Runtime/SdkRuntime.cs` file: the `HttpClient` wrapper every generated client is built on.\n *\n * Nothing here comes from outside the BCL, so a generated SDK restores and builds with no NuGet\n * feed at all. The TypeScript, Python and Kotlin SDKs likewise read and write their own bodies\n * rather than delegating to a content-negotiation layer.\n */\n\n/** Generate `Runtime/SdkRuntime.cs` for `namespaceName`. Content depends on nothing but the namespace. */\nexport function generateRuntimeCs(namespaceName: string): string {\n return `// <auto-generated/>\n// Generated by @contractkit/plugin-csharp. Do not edit manually.\n#nullable enable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ${namespaceName}.Runtime;\n\n/// <summary>\n/// How to reach the service.\n/// </summary>\npublic sealed class SdkOptions\n{\n /// <summary>Origin, optionally with a path prefix. Operation paths are appended to it.</summary>\n public required string BaseUrl { get; init; }\n\n /// <summary>\n /// Called once per request. Authentication belongs here: returning a fresh map each time lets a\n /// token be refreshed without rebuilding the SDK.\n /// </summary>\n public Func<CancellationToken, ValueTask<IReadOnlyDictionary<string, string>>>? Headers { get; init; }\n\n /// <summary>\n /// Supply your own client to control handlers, proxies or retries. When you do, the SDK never\n /// disposes it. Leave it null and the SDK creates and owns one.\n /// </summary>\n public HttpClient? HttpClient { get; init; }\n\n /// <summary>\n /// How bodies, query values and headers are serialized. Defaults to <see cref=\"SdkJson.Options\"/>,\n /// which carries the converters the contract's scalar types need.\n /// </summary>\n public JsonSerializerOptions Json { get; init; } = SdkJson.Options;\n}\n\n/// <summary>\n/// A status the contract does not account for.\n/// </summary>\n/// <remarks>\n/// Derives from <see cref=\"HttpRequestException\"/>, so it can be caught alongside any other client\n/// failure, and passes the status through to <c>StatusCode</c> for callers that catch the base type.\n/// </remarks>\npublic class SdkException : HttpRequestException\n{\n public SdkException(int status, string body, HttpResponseHeaders? responseHeaders = null, string? message = null)\n : base(message ?? $\"Request failed with status {status}\", null, ToStatusCode(status))\n {\n Status = status;\n Body = body;\n ResponseHeaders = responseHeaders;\n }\n\n /// <summary>The HTTP status the service returned.</summary>\n public int Status { get; }\n\n /// <summary>The raw response body, read as UTF-8 text.</summary>\n public string Body { get; }\n\n /// <summary>The response headers, when the failure came from a response rather than a missing header.</summary>\n public HttpResponseHeaders? ResponseHeaders { get; }\n\n private bool _jsonParsed;\n private JsonElement? _json;\n\n /// <summary>\n /// The body parsed as JSON, or null when it is not JSON. Error contracts usually are.\n /// </summary>\n public JsonElement? Json\n {\n get\n {\n if (_jsonParsed) return _json;\n _jsonParsed = true;\n try\n {\n using var document = JsonDocument.Parse(Body);\n // Clone detaches the element from the document being disposed here.\n _json = document.RootElement.Clone();\n }\n catch (JsonException)\n {\n _json = null;\n }\n return _json;\n }\n }\n\n /// <summary>\n /// Read the error body as <typeparamref name=\"T\"/>, or null when it does not parse. Operations\n /// whose thrown statuses declare a body generate an alias naming the type to use here.\n /// </summary>\n public T? TryReadBody<T>(JsonSerializerOptions? options = null)\n where T : class\n {\n try\n {\n return JsonSerializer.Deserialize<T>(Body, options ?? SdkJson.Options);\n }\n catch (JsonException)\n {\n return null;\n }\n }\n\n private static HttpStatusCode? ToStatusCode(int status) =>\n status is >= 100 and <= 599 ? (HttpStatusCode)status : null;\n}\n\n/// <summary>\n/// One response, with its body already read.\n/// </summary>\n/// <remarks>\n/// Reading the body eagerly is what allows a generated method to check the status, then the content\n/// type, then decode, which is exactly what an operation declaring several statuses or several\n/// mimes has to do.\n/// </remarks>\npublic sealed class SdkResponse\n{\n private string? _text;\n\n public SdkResponse(HttpResponseMessage message, byte[] bytes)\n {\n Message = message;\n Bytes = bytes;\n }\n\n public HttpResponseMessage Message { get; }\n\n /// <summary>The body as raw bytes.</summary>\n public byte[] Bytes { get; }\n\n public int Status => (int)Message.StatusCode;\n\n /// <summary>The response mime without its parameters, so <c>application/json; charset=utf-8</c> matches.</summary>\n public string ContentType => Message.Content.Headers.ContentType?.MediaType ?? string.Empty;\n\n /// <summary>The body decoded as UTF-8.</summary>\n public string Text => _text ??= Encoding.UTF8.GetString(Bytes);\n\n /// <summary>\n /// The first value of a response or content header, or null when the service did not send it.\n /// </summary>\n public string? Header(string name)\n {\n if (Message.Headers.TryGetValues(name, out var values)) return values.FirstOrDefault();\n if (Message.Content.Headers.TryGetValues(name, out var contentValues)) return contentValues.FirstOrDefault();\n return null;\n }\n}\n\n/// <summary>\n/// One part of a multipart request body.\n/// </summary>\npublic sealed record SdkPart(string Name, HttpContent Content, string? FileName = null)\n{\n /// <summary>A plain text field.</summary>\n public static SdkPart Text(string name, string value) => new(name, new StringContent(value, Encoding.UTF8));\n\n /// <summary>A file field, sent with a filename and its own content type.</summary>\n public static SdkPart File(string name, byte[] bytes, string fileName, string contentType = \"application/octet-stream\")\n {\n var content = new ByteArrayContent(bytes);\n content.Headers.ContentType = new MediaTypeHeaderValue(contentType);\n return new SdkPart(name, content, fileName);\n }\n}\n\n/// <summary>\n/// Issues requests and turns anything the contract does not describe into an <see cref=\"SdkException\"/>.\n/// </summary>\n/// <remarks>\n/// Every value bound for a path, query, header or form field is turned into text by serializing it\n/// the same way it would be serialized into a JSON body. That is what keeps a <c>Guid</c>, a\n/// <c>DateTimeOffset</c>, a <c>TimeSpan</c> or an enum spelled identically wherever it appears in a\n/// request, without a line of per-type code in the generator.\n/// </remarks>\npublic sealed class SdkHttp : IDisposable\n{\n private readonly SdkOptions _options;\n private readonly bool _ownsClient;\n\n public SdkHttp(SdkOptions options)\n {\n _options = options;\n _ownsClient = options.HttpClient is null;\n Client = options.HttpClient ?? new HttpClient();\n Json = options.Json;\n }\n\n public HttpClient Client { get; }\n\n public JsonSerializerOptions Json { get; }\n\n /// <summary>\n /// Send one request and read its body.\n /// </summary>\n /// <remarks>\n /// <c>expectStatuses</c> carries the statuses the operation declares as outcomes rather than\n /// failures, such as a 404 the contract gives a meaning. Everything outside 2xx and that set\n /// throws.\n /// </remarks>\n /// <exception cref=\"SdkException\">On a status the contract does not declare.</exception>\n public async Task<SdkResponse> ExecuteAsync(\n HttpMethod method,\n string path,\n IEnumerable<KeyValuePair<string, string>>? query = null,\n IEnumerable<KeyValuePair<string, string>>? headers = null,\n HttpContent? content = null,\n IReadOnlyCollection<int>? expectStatuses = null,\n CancellationToken cancellationToken = default)\n {\n using var request = new HttpRequestMessage(method, BuildUrl(path, query));\n if (content is not null) request.Content = content;\n\n if (_options.Headers is not null)\n {\n foreach (var entry in await _options.Headers(cancellationToken).ConfigureAwait(false))\n {\n request.Headers.TryAddWithoutValidation(entry.Key, entry.Value);\n }\n }\n\n if (headers is not null)\n {\n foreach (var entry in headers)\n {\n request.Headers.TryAddWithoutValidation(entry.Key, entry.Value);\n }\n }\n\n var message = await Client.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);\n var bytes = await message.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);\n var response = new SdkResponse(message, bytes);\n\n var status = response.Status;\n if ((status < 200 || status > 299) && (expectStatuses is null || !expectStatuses.Contains(status)))\n {\n throw new SdkException(status, response.Text, message.Headers);\n }\n\n return response;\n }\n\n /// <summary>Decode a JSON response body.</summary>\n /// <exception cref=\"SdkException\">When the body is JSON null.</exception>\n public T ReadJson<T>(SdkResponse response)\n {\n var value = JsonSerializer.Deserialize<T>(response.Bytes, Json);\n if (value is null)\n {\n throw new SdkException(response.Status, response.Text, response.Message.Headers, \"Response body was null\");\n }\n\n return value;\n }\n\n /// <summary>\n /// Read a response header the contract declares as required.\n /// </summary>\n /// <exception cref=\"SdkException\">When the service did not send it, since the caller was promised a value.</exception>\n public string RequireHeader(SdkResponse response, string name) =>\n response.Header(name)\n ?? throw new SdkException(response.Status, response.Text, response.Message.Headers, $\"Response is missing the required header '{name}'\");\n\n /// <summary>Join path segments onto the base URL. Each segment is already escaped.</summary>\n public string Path(params string[] segments) => segments.Length == 0 ? string.Empty : \"/\" + string.Join(\"/\", segments);\n\n /// <summary>The escaped text form of a single value, for use as a path segment.</summary>\n public string Segment<T>(T value) => Uri.EscapeDataString(ScalarText(JsonSerializer.SerializeToElement(value, Json)) ?? string.Empty);\n\n /// <summary>\n /// Every property of <paramref name=\"value\"/> as a key and value pair. A list property repeats\n /// its key; a null property is omitted.\n /// </summary>\n public IEnumerable<KeyValuePair<string, string>> Params<T>(T value)\n {\n if (value is null) yield break;\n\n var element = JsonSerializer.SerializeToElement(value, Json);\n if (element.ValueKind != JsonValueKind.Object) yield break;\n\n foreach (var property in element.EnumerateObject())\n {\n if (property.Value.ValueKind == JsonValueKind.Array)\n {\n foreach (var item in property.Value.EnumerateArray())\n {\n if (ScalarText(item) is { } itemText) yield return new KeyValuePair<string, string>(property.Name, itemText);\n }\n }\n else if (ScalarText(property.Value) is { } text)\n {\n yield return new KeyValuePair<string, string>(property.Name, text);\n }\n }\n }\n\n /// <summary>A JSON body. Sent as a buffered string so the request carries a Content-Length.</summary>\n public HttpContent JsonContent<T>(T value, string mediaType) =>\n new StringContent(JsonSerializer.Serialize(value, Json), Encoding.UTF8, mediaType);\n\n /// <summary>A form-encoded body, built from the same property walk as the query string.</summary>\n public HttpContent FormContent<T>(T value) => new FormUrlEncodedContent(Params(value));\n\n /// <summary>A multipart body.</summary>\n public HttpContent MultipartContent(IEnumerable<SdkPart> parts)\n {\n var content = new MultipartFormDataContent();\n foreach (var part in parts)\n {\n if (part.FileName is null) content.Add(part.Content, part.Name);\n else content.Add(part.Content, part.Name, part.FileName);\n }\n\n return content;\n }\n\n /// <summary>A text body with an explicit mime.</summary>\n public HttpContent TextContent(string value, string mediaType) => new StringContent(value, Encoding.UTF8, mediaType);\n\n /// <summary>A binary body with an explicit mime.</summary>\n public HttpContent BinaryContent(byte[] value, string mediaType)\n {\n var content = new ByteArrayContent(value);\n content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);\n return content;\n }\n\n /// <summary>The text a scalar JSON value travels as outside a body, or null when it is absent.</summary>\n public static string? ScalarText(JsonElement element) =>\n element.ValueKind switch\n {\n JsonValueKind.Null or JsonValueKind.Undefined => null,\n JsonValueKind.String => element.GetString(),\n JsonValueKind.True => \"true\",\n JsonValueKind.False => \"false\",\n _ => element.GetRawText(),\n };\n\n public void Dispose()\n {\n if (_ownsClient) Client.Dispose();\n }\n\n private string BuildUrl(string path, IEnumerable<KeyValuePair<string, string>>? query)\n {\n var builder = new StringBuilder(_options.BaseUrl.TrimEnd('/')).Append(path);\n if (query is null) return builder.ToString();\n\n var first = true;\n foreach (var entry in query)\n {\n builder.Append(first ? '?' : '&');\n first = false;\n builder.Append(Uri.EscapeDataString(entry.Key)).Append('=').Append(Uri.EscapeDataString(entry.Value));\n }\n\n return builder.ToString();\n }\n}\n`;\n}\n","/**\n * The `Runtime/Converters.cs` file: the shared `JsonSerializerOptions` and the converters for the\n * three ContractKit scalars whose BCL type does not serialize the way the contract says it travels.\n *\n * These live in the generated output rather than in a published NuGet package so the SDK has no\n * dependency at all. The same choice the Python plugin makes with `_base_client.py` and the Kotlin\n * plugin with `Serializers.kt`.\n *\n * Enums, unions and tuples are not handled here: each carries a `[JsonConverter]` attribute of its\n * own, so it serializes correctly under any options. These three are options-level, which is why\n * anything serializing a generated model by hand has to pass `SdkJson.Options`.\n */\n\n/** Generate `Runtime/Converters.cs` for `namespaceName`. Content depends on nothing but the namespace. */\nexport function generateConvertersCs(namespaceName: string): string {\n return `// <auto-generated/>\n// Generated by @contractkit/plugin-csharp. Do not edit manually.\n#nullable enable\n\nusing System;\nusing System.Buffers;\nusing System.Globalization;\nusing System.Numerics;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Xml;\n\nnamespace ${namespaceName}.Runtime;\n\n/// <summary>\n/// How the SDK reads and writes JSON.\n/// </summary>\n/// <remarks>\n/// Unknown properties are skipped, which is the default, so a service adding a field does not break\n/// an older client. Serialize a generated model with these options: three of the contract's scalar\n/// types need the converters registered here.\n/// </remarks>\npublic static class SdkJson\n{\n public static readonly JsonSerializerOptions Options = CreateOptions();\n\n private static JsonSerializerOptions CreateOptions()\n {\n var options = new JsonSerializerOptions();\n options.Converters.Add(new BigIntegerConverter());\n options.Converters.Add(new DecimalStringConverter());\n options.Converters.Add(new IsoTimeSpanConverter());\n return options;\n }\n}\n\n/// <summary>\n/// An arbitrary-precision integer. Written as a plain digit string.\n/// </summary>\n/// <remarks>\n/// Reading accepts a digit string, the <c>123n</c> form the TypeScript SDK writes, and a JSON\n/// number, so a body written by any ContractKit client reads back here.\n/// </remarks>\npublic sealed class BigIntegerConverter : JsonConverter<BigInteger>\n{\n public override BigInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.String)\n {\n var text = reader.GetString() ?? throw new JsonException(\"Expected a digit string for a bigint.\");\n return BigInteger.Parse(text.TrimEnd('n'), NumberStyles.Integer, CultureInfo.InvariantCulture);\n }\n\n if (reader.TokenType == JsonTokenType.Number)\n {\n // Read the raw token rather than a long: the value may be wider than any BCL integer,\n // which is the whole reason the contract called it a bigint.\n var raw = Encoding.UTF8.GetString(reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan);\n return BigInteger.Parse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture);\n }\n\n throw new JsonException($\"Expected a JSON string or number for a bigint, got {reader.TokenType}.\");\n }\n\n public override void Write(Utf8JsonWriter writer, BigInteger value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));\n }\n}\n\n/// <summary>\n/// An exact decimal number. Travels as a quoted JSON string, never as a JSON number.\n/// </summary>\n/// <remarks>\n/// A JSON number has already been through a double by the time it reaches this converter, so the\n/// precision the contract asked for is gone. Reading an unquoted number is rejected for that\n/// reason, which matches the Kotlin SDK and the server's own schema.\n/// </remarks>\npublic sealed class DecimalStringConverter : JsonConverter<decimal>\n{\n public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected a quoted decimal string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected a decimal string.\");\n return decimal.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);\n }\n\n public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));\n }\n}\n\n/// <summary>\n/// A duration, as an ISO 8601 string such as <c>PT1H30M</c>.\n/// </summary>\n/// <remarks>\n/// System.Text.Json writes a <c>TimeSpan</c> as <c>d.hh:mm:ss</c> by default, which no other\n/// ContractKit SDK would read, so this converter is not optional.\n/// </remarks>\npublic sealed class IsoTimeSpanConverter : JsonConverter<TimeSpan>\n{\n public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected an ISO 8601 duration string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected an ISO 8601 duration string.\");\n try\n {\n return XmlConvert.ToTimeSpan(text);\n }\n catch (FormatException error)\n {\n throw new JsonException($\"'{text}' is not an ISO 8601 duration.\", error);\n }\n }\n\n public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(XmlConvert.ToString(value));\n }\n}\n`;\n}\n","/**\n * The project file a generated SDK needs to build on its own.\n *\n * Emitted with `ifAbsent`, so it is created once and then belongs to the user: a project will add a\n * package id, a version, an analyzer set and a signing key of its own, and regenerating over that\n * would throw the work away. Generated C# sources are rewritten every run; this is not.\n */\n\n/**\n * What the scaffold pins. One object so a bump is one edit.\n *\n * There is deliberately no dependency list to go with it: the generated SDK uses only\n * `System.Text.Json` and `HttpClient` from the shared framework, so `dotnet build` restores with no\n * NuGet feed reachable at all.\n */\nexport const SCAFFOLD_VERSIONS = {\n targetFramework: 'net10.0',\n} as const;\n\n/**\n * Generate `<SdkName>.csproj`.\n *\n * `ImplicitUsings` is off because generated files carry an explicit `using` block of their own, and\n * leaving it on would make the output depend on the SDK's implicit set rather than on what the\n * generator wrote.\n */\nexport function generateCsproj(namespaceName: string, sdkName: string): string {\n return `<!-- Created once by @contractkit/plugin-csharp. Yours to edit: it is never regenerated. -->\n<Project Sdk=\"Microsoft.NET.Sdk\">\n\n <PropertyGroup>\n <TargetFramework>${SCAFFOLD_VERSIONS.targetFramework}</TargetFramework>\n <Nullable>enable</Nullable>\n <ImplicitUsings>disable</ImplicitUsings>\n <RootNamespace>${namespaceName}</RootNamespace>\n <AssemblyName>${sdkName}</AssemblyName>\n </PropertyGroup>\n\n</Project>\n`;\n}\n"],"mappings":";AAAA,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,YAAY,WAAW,cAAc,aAAa,QAAQ,WAAW,qBAAqB;AAanG;AAAA,EACI,mBAAAA;AAAA,EACA;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;;;ACtBP,SAAS,iBAAiB,wBAAwB,wBAAwB,sBAAsB;;;ACazF,IAAM,kBAAuC,oBAAI,IAAI;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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,YAAW,QAAQ,MAAM,MAAO,MAAK,IAAI,IAAI;AAAA,EAClE;AACA,SAAO;AACX;AAGA,SAAS,aAAa,cAA2C;AAC7D,MAAI,CAAC,WAAW,YAAY,EAAG,QAAO,yBAAyB,sBAAsB;AACrF,MAAI;AACA,WAAO,yBAAyB,aAAa,cAAc,OAAO,CAAC;AAAA,EACvE,QAAQ;AACJ,WAAO,yBAAyB,sBAAsB;AAAA,EAC1D;AACJ;AAGA,SAAS,cAAc,cAAsB,UAAqC;AAC9E,MAAI;AACA,cAAU,QAAQ,YAAY,GAAG,EAAE,WAAW,KAAK,CAAC;AACpD,kBAAc,cAAc,6BAA6B,QAAQ,GAAG,OAAO;AAAA,EAC/E,QAAQ;AAAA,EAER;AACJ;AAOA,SAAS,iBAAiB,QAAgB,UAA0B;AAChE,MAAI,SAAS,WAAW,EAAG;AAC3B,QAAM,cAAc,oBAAI,IAAY;AACpC,aAAW,OAAO,UAAU;AACxB,UAAM,MAAM,QAAQ,QAAQ,GAAG;AAC/B,QAAI,WAAW,GAAG,GAAG;AACjB,aAAO,KAAK,EAAE,OAAO,KAAK,CAAC;AAC3B,kBAAY,IAAI,KAAK,KAAK,IAAI,CAAC;AAAA,IACnC;AAAA,EACJ;AACA,aAAW,OAAO,aAAa;AAC3B,QAAI,UAAU;AACd,WAAO,QAAQ,WAAW,MAAM,KAAK,YAAY,QAAQ;AACrD,UAAI;AACA,YAAI,YAAY,OAAO,EAAE,WAAW,GAAG;AACnC,oBAAU,OAAO;AACjB,oBAAU,KAAK,SAAS,IAAI;AAAA,QAChC,OAAO;AACH;AAAA,QACJ;AAAA,MACJ,QAAQ;AACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":["buildModelIndex","collectTypeRefs","lines","resolveEffectiveFields","resolveEffectiveFields","decl","buildModelIndex","collectTypeRefs"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/codegen-models.ts","../src/naming.ts","../src/codegen-client.ts","../src/codegen-sdk.ts","../src/hoist.ts","../src/runtime.ts","../src/runtime-converters.ts","../src/runtime-polyfills.ts","../src/scaffold.ts"],"sourcesContent":["import { dirname, join, resolve } from 'node:path';\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, writeFileSync } from 'node:fs';\nimport type {\n ContractKitPlugin,\n ContractRootNode,\n ContractTypeNode,\n IncrementalManifest,\n IncrementalOutputFile,\n IncrementalUnit,\n ModelNode,\n OpRootNode,\n ParamSource,\n PluginContext,\n} from '@contractkit/core';\nimport {\n buildModelIndex,\n collectTransitiveModelRefs,\n collectTypeRefs,\n emptyIncrementalManifest,\n hashFingerprint,\n parseIncrementalManifest,\n runIncrementalCodegen,\n serializeIncrementalManifest,\n} from '@contractkit/core';\nimport { generateCSharpModels, resolveModelsWithInput, type CSharpDateTypes } from './codegen-models.js';\nimport { deriveClientClassName, deriveClientPropertyName, generateCSharpClient, hasPublicOperations } from './codegen-client.js';\nimport { generateSdkCs, type SdkAggregatorClient } from './codegen-sdk.js';\nimport { collectHoistedTypes } from './hoist.js';\nimport { generateRuntimeCs } from './runtime.js';\nimport { generateConvertersCs } from './runtime-converters.js';\nimport { generatePolyfillsCs } from './runtime-polyfills.js';\nimport { DEFAULT_TARGET_FRAMEWORKS, generateCsproj, type CSharpTargetFramework } from './scaffold.js';\nimport { CSHARP_KEYWORDS, deriveCSharpFileBase } from './naming.js';\n\nexport interface CSharpSdkPluginConfig {\n /** Output directory relative to rootDir (default: \"csharp-sdk\") */\n baseDir?: string;\n /** Root namespace for the generated sources, e.g. \"Acme.Sdk\" (default: \"ContractKit.Sdk\") */\n namespace?: string;\n /** Aggregator class name (default: \"Sdk\"). Also the assembly name when scaffolding. */\n sdkName?: string;\n /**\n * Whether to emit client methods for operations marked `internal`. Defaults to `false` —\n * internal ops are omitted so consumers don't pick them up.\n */\n includeInternal?: boolean;\n /** Emit `<SdkName>.csproj` once, as a user-owned file. Never overwritten. */\n scaffold?: boolean;\n /**\n * The frameworks the SDK is built for (default: `[\"net10.0\"]`).\n *\n * Naming `netstandard2.0` is what makes the output usable from a UWP or .NET Framework project:\n * `Runtime/Polyfills.cs` is emitted alongside the rest, and a scaffolded `.csproj` multi-targets\n * and references `System.Text.Json` on that leg. Convention puts the oldest framework first.\n */\n targetFrameworks?: CSharpTargetFramework[];\n /**\n * Which C# type a contract's `date` maps to (default: `\"dateonly\"`).\n *\n * `\"datetime\"` maps it to `DateTime` at midnight with an unspecified kind, for a UI stack whose\n * date controls bind to that and nothing else — XAML's `DatePicker` among them. It applies to\n * every framework the SDK is built for, so the public surface never differs between them.\n *\n * `time` is `TimeOnly` either way, because `duration` already maps to `TimeSpan` and a `time`\n * carried as one would go out as `PT9H30M`.\n */\n dateTypes?: CSharpDateTypes;\n}\n\n/**\n * Bumped when the C# codegen output shape changes in a way that should invalidate every per-file\n * fingerprint, so a plugin upgrade forces full regeneration even when no `.ck` file has changed.\n */\nexport const CSHARP_CODEGEN_VERSION = '2';\n\nexport type { CSharpTargetFramework } from './scaffold.js';\nexport type { CSharpDateTypes } from './codegen-models.js';\n\nconst CACHE_MANIFEST_FILENAME = 'csharp-manifest.json';\nconst DEFAULT_BASE_DIR = 'csharp-sdk';\nconst DEFAULT_NAMESPACE = 'ContractKit.Sdk';\nconst DEFAULT_SDK_NAME = 'Sdk';\nconst DEFAULT_DATE_TYPES: CSharpDateTypes = 'dateonly';\n\nconst plugin: ContractKitPlugin = {\n name: 'csharp-sdk',\n async generateTargets(inputs, ctx) {\n const config = ctx.options as CSharpSdkPluginConfig;\n await runCSharpCodegen(inputs, ctx, config, ctx.rootDir);\n },\n};\n\nexport default plugin;\n\nexport function createCSharpSdkPlugin(config: CSharpSdkPluginConfig, rootDir: string): ContractKitPlugin {\n return {\n name: 'csharp-sdk',\n async generateTargets(inputs, ctx) {\n await runCSharpCodegen(inputs, ctx, config, rootDir);\n },\n };\n}\n\nconst NAMESPACE_RE = /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*$/;\nconst SDK_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Reject config that would generate C# which cannot compile. These are runtime checks, not just\n * types: config arrives as JSON, so the TypeScript interface constrains programmatic callers only.\n */\nexport function assertValidConfig(config: CSharpSdkPluginConfig): void {\n const { namespace, sdkName } = config;\n if (namespace !== undefined) {\n if (typeof namespace !== 'string' || !NAMESPACE_RE.test(namespace)) {\n throw new Error(\n `plugin-csharp: namespace '${String(namespace)}' is not a valid C# namespace — expected dot-separated identifiers, e.g. 'Acme.Sdk'.`,\n );\n }\n const keyword = namespace.split('.').find(segment => CSHARP_KEYWORDS.has(segment));\n if (keyword) {\n throw new Error(`plugin-csharp: namespace '${namespace}' contains the C# keyword '${keyword}', which cannot appear in a namespace.`);\n }\n }\n if (sdkName !== undefined) {\n if (typeof sdkName !== 'string' || !SDK_NAME_RE.test(sdkName)) {\n throw new Error(`plugin-csharp: sdkName '${String(sdkName)}' is not a valid C# class name.`);\n }\n if (CSHARP_KEYWORDS.has(sdkName)) {\n throw new Error(`plugin-csharp: sdkName '${sdkName}' is a C# keyword.`);\n }\n }\n for (const key of ['includeInternal', 'scaffold'] as const) {\n const value = config[key];\n if (value !== undefined && typeof value !== 'boolean') {\n throw new Error(`plugin-csharp: ${key} must be a boolean — got ${JSON.stringify(value)}.`);\n }\n }\n assertValidTargetFrameworks(config.targetFrameworks);\n if (config.dateTypes !== undefined && !DATE_TYPES.includes(config.dateTypes)) {\n throw new Error(`plugin-csharp: dateTypes ${JSON.stringify(config.dateTypes)} is not supported — expected one of ${DATE_TYPES.join(', ')}.`);\n }\n}\n\n/** The C# types a contract's `date` can map to. */\nconst DATE_TYPES: readonly CSharpDateTypes[] = ['dateonly', 'datetime'];\n\n/** Every framework the scaffold knows how to write a project file for. */\nconst TARGET_FRAMEWORKS: readonly CSharpTargetFramework[] = ['netstandard2.0', 'net10.0'];\n\nfunction assertValidTargetFrameworks(frameworks: CSharpSdkPluginConfig['targetFrameworks']): void {\n if (frameworks === undefined) return;\n if (!Array.isArray(frameworks) || frameworks.length === 0) {\n throw new Error(`plugin-csharp: targetFrameworks must be a non-empty array — got ${JSON.stringify(frameworks)}.`);\n }\n const seen = new Set<string>();\n for (const framework of frameworks) {\n if (typeof framework !== 'string' || !TARGET_FRAMEWORKS.includes(framework)) {\n throw new Error(\n `plugin-csharp: targetFrameworks entry ${JSON.stringify(framework)} is not supported — expected one of ${TARGET_FRAMEWORKS.join(', ')}.`,\n );\n }\n if (seen.has(framework)) {\n throw new Error(`plugin-csharp: targetFrameworks lists '${framework}' twice.`);\n }\n seen.add(framework);\n }\n}\n\n/**\n * Shared orchestration. Builds per-file fingerprints, reuses unchanged outputs from the manifest,\n * regenerates only the affected files, and rewrites the shared runtime and aggregator every run\n * (they are cheap and depend only on the set of public clients).\n *\n * Honors `ctx.cacheEnabled`, so `--force` bypasses the per-file cache.\n */\nasync function runCSharpCodegen(\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n ctx: PluginContext,\n config: CSharpSdkPluginConfig,\n rootDir: string,\n): Promise<void> {\n assertValidConfig(config);\n\n const { contractRoots } = inputs;\n const namespaceName = config.namespace ?? DEFAULT_NAMESPACE;\n const sdkName = config.sdkName ?? DEFAULT_SDK_NAME;\n const targetFrameworks = config.targetFrameworks ?? DEFAULT_TARGET_FRAMEWORKS;\n const dateTypes = config.dateTypes ?? DEFAULT_DATE_TYPES;\n const outDir = resolve(rootDir, config.baseDir ?? DEFAULT_BASE_DIR);\n const manifestPath = resolve(ctx.cacheDir, CACHE_MANIFEST_FILENAME);\n\n // Every model shares one C# namespace, so a cross-file reference resolves by name and the only\n // cross-file input a models unit has is which names carry an Input variant.\n const allModels: ModelNode[] = contractRoots.flatMap(root => root.models);\n const modelIndex = buildModelIndex(allModels);\n // Resolved once over every model, so the hoisting pass and each file's renderer agree on which\n // names carry an `Input` variant.\n const modelsWithInput = resolveModelsWithInput(allModels, inputs.modelsWithInput);\n const modelsWithInputArray = [...modelsWithInput].sort();\n\n // Names for the anonymous shapes — unions, inline objects, field-level enums, tuples — that C#\n // needs a declaration for. Computed across every file at once: a discriminated union declared in\n // one file makes member records generated in other files implement its interface.\n const hoisted = collectHoistedTypes(contractRoots, {\n modelIndex,\n modelsWithInput,\n warn: (message, file) => ctx.warn?.(message, file),\n });\n\n const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(CSHARP_CODEGEN_VERSION);\n const units: IncrementalUnit[] = [];\n const clients: SdkAggregatorClient[] = [];\n\n for (const root of contractRoots) {\n const relPath = `Models/${deriveCSharpFileBase(root.file)}.cs`;\n const ownNames = new Set(root.models.map(m => m.name));\n const referenced = referencedModelNames(root);\n const relevantInputModels = modelsWithInputArray.filter(name => ownNames.has(name) || referenced.has(name));\n // A base declared in another file contributes its fields to a record generated here, so the\n // fingerprint has to move when that base does.\n const externalBases = [...referenced]\n .filter(name => !ownNames.has(name))\n .sort()\n .map(name => modelIndex.get(name))\n .filter((m): m is ModelNode => m !== undefined);\n\n // Declarations this file owns, and the interfaces its records implement, are both decided by\n // the whole project, so they belong in the fingerprint alongside the file.\n const ownedDeclarations = (hoisted.byFile.get(root.file) ?? []).map(d => ({ kind: d.kind, name: d.name, needsInput: d.needsInput }));\n const declaredMemberships = [...ownNames]\n .sort()\n .map(name => [name, hoisted.memberships.get(name) ?? []] as const)\n .filter(([, unions]) => unions.length > 0);\n\n const fingerprint = hashFingerprint({\n kind: 'models',\n v: CSHARP_CODEGEN_VERSION,\n relPath,\n namespace: namespaceName,\n dateTypes,\n root,\n externalBases,\n modelsWithInput: relevantInputModels,\n ownedDeclarations,\n declaredMemberships,\n });\n\n units.push({\n key: `models::${relPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: relPath,\n content: generateCSharpModels(root, {\n namespace: namespaceName,\n dateTypes,\n modelsWithInput,\n modelIndex,\n hoisted,\n warn: message => ctx.warn?.(message, root.file),\n }),\n },\n ],\n });\n }\n\n // ── Per-op-root client files ─────────────────────────────────────────────\n for (const root of inputs.opRoots) {\n if (!hasPublicOperations(root, config.includeInternal)) continue;\n const relPath = `Clients/${deriveClientClassName(root.file)}.cs`;\n clients.push({ className: deriveClientClassName(root.file), propertyName: deriveClientPropertyName(root.file) });\n\n const referenced = referencedOpModels(root, modelIndex);\n const relevantInputModels = modelsWithInputArray.filter(name => referenced.has(name));\n // A client names the models it takes and returns, so the shapes behind those names — and\n // the declarations hoisted out of them — are part of what this file depends on.\n const referencedModels = [...referenced]\n .sort()\n .map(name => modelIndex.get(name))\n .filter((m): m is ModelNode => m !== undefined);\n\n const fingerprint = hashFingerprint({\n kind: 'client',\n v: CSHARP_CODEGEN_VERSION,\n relPath,\n namespace: namespaceName,\n dateTypes,\n root,\n referencedModels,\n modelsWithInput: relevantInputModels,\n includeInternal: config.includeInternal ?? false,\n });\n\n units.push({\n key: `client::${relPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: relPath,\n content: generateCSharpClient(root, {\n namespace: namespaceName,\n dateTypes,\n modelsWithInput,\n modelIndex,\n hoisted,\n includeInternal: config.includeInternal,\n warn: message => ctx.warn?.(message, root.file),\n }),\n },\n ],\n });\n }\n\n // The runtime is a constant, and the aggregator depends only on the list of public clients.\n // Both are small enough that rewriting them every run beats a cache entry.\n const globalFiles: IncrementalOutputFile[] = [\n { relativePath: 'Runtime/Converters.cs', content: generateConvertersCs(namespaceName, dateTypes) },\n { relativePath: 'Runtime/SdkRuntime.cs', content: generateRuntimeCs(namespaceName) },\n { relativePath: `${sdkName}.cs`, content: generateSdkCs(namespaceName, sdkName, clients) },\n ];\n\n // Only a build that includes netstandard2.0 has anything to fill in. Dropping the framework from\n // the config drops the file, which the incremental pass then deletes as an orphan.\n if (targetFrameworks.includes('netstandard2.0')) {\n globalFiles.push({ relativePath: 'Runtime/Polyfills.cs', content: generatePolyfillsCs(namespaceName) });\n }\n\n // `ifAbsent` marks this user-owned: written once, never overwritten, and never removed as an\n // orphan when the generated tree changes around it.\n if (config.scaffold) {\n globalFiles.push({\n relativePath: `${sdkName}.csproj`,\n content: generateCsproj(namespaceName, sdkName, targetFrameworks),\n ifAbsent: true,\n });\n }\n\n const result = runIncrementalCodegen({\n codegenVersion: CSHARP_CODEGEN_VERSION,\n prevManifest,\n globalFiles,\n units,\n fileExists: relPath => existsSync(resolve(outDir, relPath)),\n });\n\n deleteStalePaths(outDir, result.deletedPaths);\n\n for (const { relativePath, content, ifAbsent } of result.filesToWrite) {\n ctx.emitFile(resolve(outDir, relativePath), content, ifAbsent ? { ifAbsent: true } : undefined);\n }\n\n writeManifest(manifestPath, result.manifest);\n}\n\n/** Every model name an operations file names, transitively, so the client's inputs are covered. */\nfunction referencedOpModels(root: OpRootNode, modelIndex: Map<string, ModelNode>): Set<string> {\n const seeds: ContractTypeNode[] = [];\n const addParamSource = (source: ParamSource | undefined): void => {\n if (!source) return;\n if (source.kind === 'params') seeds.push(...source.nodes.map(n => n.type));\n else if (source.kind === 'ref') seeds.push({ kind: 'ref', name: source.name });\n else seeds.push(source.node);\n };\n\n for (const route of root.routes) {\n addParamSource(route.params);\n for (const op of route.operations) {\n addParamSource(op.query);\n addParamSource(op.headers);\n for (const body of op.request?.bodies ?? []) seeds.push(body.bodyType);\n for (const response of op.responses) {\n for (const body of response.bodies) seeds.push(body.bodyType);\n for (const header of response.headers ?? []) seeds.push(header.type);\n }\n }\n }\n\n return collectTransitiveModelRefs(seeds, modelIndex);\n}\n\n/** Every model name a contract root references but may not define, including its bases. */\nfunction referencedModelNames(root: ContractRootNode): Set<string> {\n const refs = new Set<string>();\n for (const model of root.models) {\n if (model.type) collectTypeRefs(model.type, refs);\n for (const f of model.fields) collectTypeRefs(f.type, refs);\n if (model.bases) for (const base of model.bases) refs.add(base);\n }\n return refs;\n}\n\n/** Read the previous run's manifest. Returns an empty manifest when missing or unreadable. */\nfunction readManifest(manifestPath: string): IncrementalManifest {\n if (!existsSync(manifestPath)) return emptyIncrementalManifest(CSHARP_CODEGEN_VERSION);\n try {\n return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return emptyIncrementalManifest(CSHARP_CODEGEN_VERSION);\n }\n}\n\n/** Write the manifest. Errors are swallowed so a broken cache never blocks the build. */\nfunction writeManifest(manifestPath: string, manifest: IncrementalManifest): void {\n try {\n mkdirSync(dirname(manifestPath), { recursive: true });\n writeFileSync(manifestPath, serializeIncrementalManifest(manifest), 'utf-8');\n } catch {\n // best-effort\n }\n}\n\n/**\n * Delete paths from the prior manifest that aren't produced this run, then prune the directories\n * they leave empty. The output tree is nested (`Models/`, `Clients/`, `Runtime/`), so a renamed\n * `.ck` file would otherwise leave an empty directory behind.\n */\nfunction deleteStalePaths(outDir: string, relPaths: string[]): void {\n if (relPaths.length === 0) return;\n const removedDirs = new Set<string>();\n for (const rel of relPaths) {\n const abs = resolve(outDir, rel);\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(join(abs, '..'));\n }\n }\n for (const dir of removedDirs) {\n let current = dir;\n while (current.startsWith(outDir) && current !== outDir) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = join(current, '..');\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n","import type { ContractRootNode, ContractTypeNode, FieldDefault, FieldNode, ModelNode, ScalarTypeNode } from '@contractkit/core';\nimport { buildModelIndex, computeModelsWithInput, resolveEffectiveFields, topoSortModels } from '@contractkit/core';\nimport type { HoistedDecl, HoistResult } from './hoist.js';\nimport { quoteCSharpString, safeMemberName, toCSharpEnumMemberName, toCSharpPropertyName, xmlDocLines } from './naming.js';\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Which C# type a contract's `date` maps to.\n *\n * `dateonly` is `DateOnly`, the type the framework added for exactly this. `datetime` is `DateTime`\n * at midnight with an unspecified kind, for a UI stack whose date controls bind to that and nothing\n * else — XAML's `DatePicker` among them. The choice applies to every framework the SDK is built for,\n * so the public surface never differs between them.\n *\n * `time` is `TimeOnly` either way: `duration` already maps to `TimeSpan`, and serialization dispatches\n * on the CLR type, so a `time` carried as a `TimeSpan` would go out as `PT9H30M`.\n */\nexport type CSharpDateTypes = 'dateonly' | 'datetime';\n\nexport interface CSharpModelCodegenOptions {\n /** Root namespace the SDK is generated into. Models land in `<namespace>.Models`. */\n namespace: string;\n /** Which C# type a `date` maps to (default: `dateonly`). */\n dateTypes?: CSharpDateTypes;\n /** Model names that have a distinct `Input` variant, including ones declared in other files. */\n modelsWithInput?: ReadonlySet<string>;\n /**\n * Every model in the project, for flattening bases and intersections. Defaults to an index of\n * this root's own models, which is enough for a single-file project and for unit tests.\n */\n modelIndex?: ReadonlyMap<string, ModelNode>;\n /** Names assigned to anonymous types by {@link collectHoistedTypes}, across the whole project. */\n hoisted?: HoistResult;\n warn?: (message: string) => void;\n}\n\n/**\n * The `using` block every generated models file carries.\n *\n * There is no import tracker, unlike the Kotlin plugin: every type the models can name is in the\n * base class library, so the set is fixed. An unused `using` is not a compiler warning, and pinning\n * the block keeps the output stable and free of the ordering churn a tracker would produce.\n *\n * The SDK's own runtime namespace is added to this list per file, because it needs the namespace\n * name. It is where `DateOnly` and `TimeOnly` come from on a framework too old to have them: the\n * polyfills are declared there and nowhere else, so the same short spelling resolves to the\n * framework's type wherever the framework has one, with no conditional code in a model.\n */\nconst MODEL_USINGS = [\n 'using System;',\n 'using System.Collections.Generic;',\n 'using System.Numerics;',\n 'using System.Text.Json;',\n 'using System.Text.Json.Serialization;',\n] as const;\n\n/**\n * Generate the C# models file for one contract root: a `sealed record` per model, plus `<Name>Input`\n * variants, enums, aliases, and the records, interfaces and converters standing in for the unions\n * and anonymous shapes this file owns.\n *\n * Every model in the project shares the single `<namespace>.Models` namespace, so a reference to a\n * model declared in another `.ck` file needs no import and resolves by name alone. That is also what\n * lets an interface declared in one file be implemented by a record generated in another.\n */\nexport function generateCSharpModels(root: ContractRootNode, opts: CSharpModelCodegenOptions): string {\n const modelsWithInput = resolveModelsWithInput(root.models, opts.modelsWithInput);\n const modelIndex = opts.modelIndex ?? buildModelIndex(root.models);\n\n const ctx: RenderContext = {\n namespace: opts.namespace,\n dateTypes: opts.dateTypes ?? 'dateonly',\n modelsWithInput,\n modelIndex,\n hoisted: opts.hoisted,\n globalAliases: [],\n warn: opts.warn,\n };\n\n const bodies: string[] = [];\n const append = (lines: string[]): void => {\n // A model whose type is a union emits nothing here — the hoisting pass owns the declaration\n // named after it — so the blank separator has to be conditional or it leaves a gap behind.\n if (lines.length === 0) return;\n bodies.push('', ...lines);\n };\n for (const model of topoSortModels(root.models)) append(generateModel(model, ctx));\n for (const decl of opts.hoisted?.byFile.get(root.file) ?? []) append(generateHoisted(decl, ctx));\n\n return renderFile(`${opts.namespace}.Models`, ctx.globalAliases, [...MODEL_USINGS, `using ${opts.namespace}.Runtime;`], bodies);\n}\n\n/**\n * The complete set of model names that need a distinct `Input` variant: the ones passed in, plus\n * the transitive closure over `models`.\n *\n * The hoisting pass and the renderer both have to agree on this — a hoisted shape whose Input twin\n * one of them thinks is unnecessary would leave the other referring to a type nobody emitted.\n */\nexport function resolveModelsWithInput(models: readonly ModelNode[], external: ReadonlySet<string> = new Set()): Set<string> {\n const seed = new Set(external);\n return new Set([...seed, ...computeModelsWithInput([...models], seed)]);\n}\n\n// ─── Render context ────────────────────────────────────────────────────────\n\ninterface RenderContext {\n namespace: string;\n dateTypes: CSharpDateTypes;\n modelsWithInput: ReadonlySet<string>;\n modelIndex: ReadonlyMap<string, ModelNode>;\n hoisted?: HoistResult;\n /** `global using` alias lines this file has to emit above its own `using` block. */\n globalAliases: string[];\n /** When set, type names render fully qualified, as a `global using` alias target must be. */\n qualify?: boolean;\n warn?: (message: string) => void;\n}\n\n/** Build a rendering context for a file outside the models namespace, such as a client. */\nexport function createRenderContext(opts: CSharpModelCodegenOptions & { modelsWithInput: ReadonlySet<string> }): RenderContext {\n return {\n namespace: opts.namespace,\n dateTypes: opts.dateTypes ?? 'dateonly',\n modelsWithInput: opts.modelsWithInput,\n modelIndex: opts.modelIndex ?? new Map(),\n hoisted: opts.hoisted,\n globalAliases: [],\n warn: opts.warn,\n };\n}\n\n/**\n * Assemble a generated C# file: header, nullable context, global aliases, usings, namespace, bodies.\n *\n * `// <auto-generated/>` turns the nullable context off, so `#nullable enable` follows it\n * explicitly. A `global using` alias has to precede every ordinary `using` in its file, which is\n * why the aliases are collected during rendering and emitted here rather than inline.\n */\nexport function renderFile(namespaceName: string, globalAliases: readonly string[], usings: readonly string[], bodies: string[]): string {\n const lines: string[] = ['// <auto-generated/>', '// Generated by @contractkit/plugin-csharp. Do not edit manually.', '#nullable enable', ''];\n if (globalAliases.length > 0) {\n lines.push(...[...globalAliases].sort());\n lines.push('');\n }\n lines.push(...usings);\n lines.push('');\n lines.push(`namespace ${namespaceName};`);\n lines.push(...bodies);\n lines.push('');\n return lines.join('\\n');\n}\n\n// ─── Type rendering ────────────────────────────────────────────────────────\n\n/**\n * Render a ContractKit type as its C# type expression. Never returns a nullable type unless the type\n * itself is one — the caller appends `?` from the field's own `optional`/`nullable` flags.\n *\n * @param forInput - When true, a reference to a model or hoisted shape with an Input variant renders\n * as `<Name>Input`.\n * @throws {Error} Via the scalar renderer, if a scalar has no C# mapping.\n */\nexport function renderCSharpType(type: ContractTypeNode, ctx: RenderContext, forInput = false): string {\n const decl = ctx.hoisted?.byNode.get(type);\n if (decl) return hoistedTypeName(decl, ctx, forInput);\n\n switch (type.kind) {\n case 'scalar':\n return renderScalar(type.name, ctx);\n case 'literal':\n return literalCSharpType(type.value, ctx);\n case 'array':\n return `${qualify('List', 'System.Collections.Generic.List', ctx)}<${renderCSharpType(type.item, ctx, forInput)}>`;\n case 'record': {\n const key = renderCSharpType(type.key, ctx, forInput);\n const value = renderCSharpType(type.value, ctx, forInput);\n const stringType = qualify('string', 'System.String', ctx);\n if (key !== stringType) {\n ctx.warn?.(\n `A record key of type '${key}' is not representable as a JSON object key; emitting Dictionary<string, ${value}>. ` +\n `Parse the key yourself, or declare the key as a string.`,\n );\n }\n return `${qualify('Dictionary', 'System.Collections.Generic.Dictionary', ctx)}<${stringType}, ${value}>`;\n }\n case 'tuple':\n // Unreachable in the real pipeline: the hoisting pass gives every tuple a record of its\n // own, so the `byNode` lookup above has already returned.\n return jsonElement(ctx);\n case 'ref': {\n const name = forInput && ctx.modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;\n return ctx.qualify ? `${ctx.namespace}.Models.${name}` : name;\n }\n case 'lazy':\n return renderCSharpType(type.inner, ctx, forInput);\n case 'union': {\n // A union with at most one non-null member never gets a declaration: it is either C#'s\n // own nullable type or nothing at all.\n const nonNull = type.members.filter(m => !isNullScalar(m));\n const nullable = nonNull.length !== type.members.length;\n if (nonNull.length === 0) return `${qualify('object', 'System.Object', ctx)}?`;\n if (nonNull.length === 1) {\n const inner = renderCSharpType(nonNull[0]!, ctx, forInput);\n return nullable && !inner.endsWith('?') ? `${inner}?` : inner;\n }\n return jsonElement(ctx);\n }\n case 'enum':\n case 'inlineObject':\n case 'intersection':\n case 'discriminatedUnion':\n // Reached only when the shape could not be given a name — a discriminated union whose\n // tag is not statically known, or a caller that skipped the hoisting pass.\n return jsonElement(ctx);\n }\n}\n\nfunction hoistedTypeName(decl: HoistedDecl, ctx: RenderContext, forInput: boolean): string {\n const bare = forInput && decl.needsInput ? `${decl.name}Input` : decl.name;\n const name = ctx.qualify ? `${ctx.namespace}.Models.${bare}` : bare;\n return decl.nullable ? `${name}?` : name;\n}\n\n/** Pick the short or the fully-qualified spelling, depending on where the type is being written. */\nfunction qualify(short: string, full: string, ctx: RenderContext): string {\n return ctx.qualify ? full : short;\n}\n\nfunction jsonElement(ctx: RenderContext): string {\n return qualify('JsonElement', 'System.Text.Json.JsonElement', ctx);\n}\n\nfunction isNullScalar(type: ContractTypeNode): boolean {\n return type.kind === 'scalar' && type.name === 'null';\n}\n\n/**\n * Map a ContractKit scalar to its C# type.\n *\n * @throws {Error} When a scalar has no mapping, so a scalar added to core fails the build here\n * rather than emitting C# that does not compile.\n */\nexport function renderScalar(name: ScalarTypeNode['name'], ctx: RenderContext): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'interval':\n return qualify('string', 'System.String', ctx);\n case 'number':\n return qualify('double', 'System.Double', ctx);\n // `int` is a JS safe integer in the source language, which overflows C#'s 32-bit int.\n case 'int':\n return qualify('long', 'System.Int64', ctx);\n case 'bigint':\n return qualify('BigInteger', 'System.Numerics.BigInteger', ctx);\n // Carried as a quoted string by DecimalStringConverter, never as a JSON number.\n case 'decimal':\n return qualify('decimal', 'System.Decimal', ctx);\n case 'boolean':\n return qualify('bool', 'System.Boolean', ctx);\n // Both carried as the wire form by a converter: `yyyy-MM-dd` and `HH:mm:ss`.\n case 'date':\n return ctx.dateTypes === 'datetime' ? qualify('DateTime', 'System.DateTime', ctx) : qualify('DateOnly', 'System.DateOnly', ctx);\n case 'time':\n return qualify('TimeOnly', 'System.TimeOnly', ctx);\n case 'datetime':\n return qualify('DateTimeOffset', 'System.DateTimeOffset', ctx);\n // Carried as ISO 8601 by IsoTimeSpanConverter, not the BCL's own `d.hh:mm:ss`.\n case 'duration':\n return qualify('TimeSpan', 'System.TimeSpan', ctx);\n case 'uuid':\n return qualify('Guid', 'System.Guid', ctx);\n case 'binary':\n return qualify('byte[]', 'System.Byte[]', ctx);\n case 'null':\n return `${qualify('object', 'System.Object', ctx)}?`;\n case 'unknown':\n case 'json':\n case 'object':\n return jsonElement(ctx);\n default: {\n const _exhaustive: never = name;\n throw new Error(`plugin-csharp: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\nfunction literalCSharpType(value: string | number | boolean, ctx: RenderContext): string {\n if (typeof value === 'string') return qualify('string', 'System.String', ctx);\n if (typeof value === 'boolean') return qualify('bool', 'System.Boolean', ctx);\n return Number.isInteger(value) ? qualify('long', 'System.Int64', ctx) : qualify('double', 'System.Double', ctx);\n}\n\n// ─── Default values ────────────────────────────────────────────────────────\n\nconst MIN_SAFE_BIGINT = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);\n\n/**\n * Whether a `bigint` field's default is written as `new BigInteger(<literal>)` rather than parsed\n * from a string. A number past 2**53 has already lost digits, so it cannot be written as a literal;\n * a bigint keeps the same cutoff so a value renders one way whichever form it arrives in.\n */\nfunction isSafeInteger(value: number | bigint): boolean {\n return typeof value === 'bigint' ? value >= MIN_SAFE_BIGINT && value <= MAX_SAFE_BIGINT : Number.isSafeInteger(value);\n}\n\n/**\n * Render a contract default as a C# expression of the field's own type. Returns `undefined` when the\n * value cannot be expressed, so the field is emitted as `required` rather than with an initializer\n * that will not compile.\n *\n * `memberNames` are the property names of the record the initializer sits in. Inside that record a\n * simple name resolves to a member before a type, so `public Rating? Rating { get; init; } =\n * Rating.Neutral;` reads the instance property and fails with CS0236. C#'s rule that lets a member\n * share its type's name applies only when the member's type is exactly that type, and `Rating?` is\n * `Nullable<Rating>`. An enum a member would shadow is written from the global namespace instead.\n */\nfunction renderDefault(\n value: FieldDefault,\n type: ContractTypeNode,\n ctx: RenderContext,\n memberNames: ReadonlySet<string> = new Set(),\n): string | undefined {\n const enumType = (name: string): string => (memberNames.has(name) ? `global::${ctx.namespace}.Models.${name}` : name);\n\n const inner = type.kind === 'lazy' ? type.inner : type;\n\n if (typeof value === 'boolean') return String(value);\n\n // A `bigint` value comes from a `bigint` field, whose case below writes it from its exact digits.\n if (typeof value === 'number' || typeof value === 'bigint') {\n if (inner.kind === 'scalar') {\n switch (inner.name) {\n case 'int':\n return `${value}L`;\n case 'number':\n return `${value}d`;\n case 'decimal':\n return `${value}m`;\n case 'bigint':\n return isSafeInteger(value) ? `new BigInteger(${value})` : `BigInteger.Parse(\"${value}\")`;\n }\n }\n return Number.isInteger(value) ? `${value}L` : `${value}d`;\n }\n\n // A string default against an enum names one of its members. When the enum was hoisted into a\n // real C# enum, that is expressible; a bare inline enum has no type to qualify.\n if (inner.kind === 'enum') {\n const decl = ctx.hoisted?.byNode.get(inner);\n if (!decl || !inner.values.includes(value)) return undefined;\n return `${enumType(decl.name)}.${enumMemberNames(inner.values).get(value)}`;\n }\n\n // The same default written against a NAMED enum contract — `rating: Rating = \"neutral\"`, where\n // `contract Rating: enum(...)` — arrives here as a ref rather than as the enum node.\n if (inner.kind === 'ref') {\n const target = ctx.modelIndex.get(inner.name);\n const targetType = target?.type?.kind === 'lazy' ? target.type.inner : target?.type;\n if (targetType?.kind !== 'enum' || !targetType.values.includes(value)) return undefined;\n return `${enumType(inner.name)}.${enumMemberNames(targetType.values).get(value)}`;\n }\n\n if (inner.kind === 'scalar') {\n switch (inner.name) {\n case 'decimal':\n return /^-?\\d+(\\.\\d+)?$/.test(value) ? `${value}m` : undefined;\n case 'bigint':\n return /^-?\\d+$/.test(value) ? `BigInteger.Parse(${quoteCSharpString(value)})` : undefined;\n case 'string':\n case 'email':\n case 'url':\n case 'interval':\n return quoteCSharpString(value);\n default:\n // date/uuid/datetime and friends have no literal syntax; leave the field required.\n return undefined;\n }\n }\n return quoteCSharpString(value);\n}\n\n// ─── Wire key casing ───────────────────────────────────────────────────────\n\n/** The key casing a contract's `format(input=)` / `format(output=)` names. */\ntype WireCase = NonNullable<ModelNode['outputCase']>;\n\n/**\n * A field name as it travels, which is not always the name the contract declares it under.\n *\n * The two transforms are spelled exactly as `plugin-typescript` spells them, deliberately: the\n * server parses and emits through that plugin's schemas, so a C# client that disagreed with it about\n * where an underscore goes would be wrong in a way no test in either package could see.\n */\nfunction applyWireCase(name: string, wireCase: WireCase | undefined): string {\n if (!wireCase || wireCase === 'camel') return name;\n if (wireCase === 'snake') return name.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/** A case that actually renames something. `camel` is the identity and is treated as absent. */\nfunction renamingCase(wireCase: WireCase | undefined): WireCase | undefined {\n return wireCase && wireCase !== 'camel' ? wireCase : undefined;\n}\n\n/**\n * Which casing one generated record's keys travel in.\n *\n * A response is decoded through `format(output=)` and a request is encoded through `format(input=)`,\n * so a model split into a read record and an `Input` twin takes one each. A model that is NOT split\n * is one record used in both directions, and a `[JsonPropertyName]` cannot spell two different key\n * sets — so a contract asking for two is reported rather than silently resolved in whichever\n * direction happens to be rendered.\n */\nfunction wireCaseFor(model: ModelNode, forInput: boolean, split: boolean, ctx: RenderContext): WireCase | undefined {\n const input = renamingCase(model.inputCase);\n const output = renamingCase(model.outputCase);\n if (split) return forInput ? input : output;\n if (input && output && input !== output) {\n ctx.warn?.(\n `Contract '${model.name}' sets format(input=${input}) and format(output=${output}), but nothing about it splits into an Input variant, ` +\n `so one C# record carries both directions and can only spell one set of keys. The generated keys follow the output casing; ` +\n `a request built from this record will send the wrong ones.`,\n );\n return output;\n }\n return output ?? input;\n}\n\n/**\n * Whether a type puts an anonymous object under a renamed model.\n *\n * Such an object is hoisted into a record of its own, which is rendered without the owning model's\n * casing — the hoisting pass records no owner to take it from. That is a real gap rather than a\n * decision, so it is reported at the one place the owner is still known.\n */\nfunction containsInlineObject(type: ContractTypeNode | undefined): boolean {\n if (!type) return false;\n switch (type.kind) {\n case 'inlineObject':\n return true;\n case 'lazy':\n return containsInlineObject(type.inner);\n case 'array':\n return containsInlineObject(type.item);\n case 'record':\n return containsInlineObject(type.value);\n case 'tuple':\n return type.items.some(containsInlineObject);\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n return (type.members ?? []).some(containsInlineObject);\n default:\n return false;\n }\n}\n\n/** Report the gap above, once per model rather than once per field. */\nfunction warnUncasedNesting(model: ModelNode, fields: readonly FieldNode[], wireCase: WireCase | undefined, ctx: RenderContext): void {\n if (!wireCase) return;\n if (!fields.some(f => containsInlineObject(f.type)) && !containsInlineObject(model.type)) return;\n ctx.warn?.(\n `Contract '${model.name}' is declared format(${model.outputCase ? 'output' : 'input'}=${wireCase}) and holds an anonymous object. ` +\n `The record hoisted out of that object keeps its declared key names, so its keys will not be ${wireCase}-cased. ` +\n `Name the shape as its own contract to fix it.`,\n );\n}\n\n// ─── Model generation ──────────────────────────────────────────────────────\n\nfunction generateModel(model: ModelNode, ctx: RenderContext): string[] {\n if (model.type) return generateAliasModel(model, ctx);\n\n const effective = effectiveFieldsFor(model, ctx);\n const needsSplit = ctx.modelsWithInput.has(model.name) || effective.some(f => f.visibility !== 'normal');\n\n if (!needsSplit) return generateRecordForModel(model.name, effective, ctx, false, model, false);\n\n const readFields = effective.filter(f => f.visibility !== 'writeonly');\n const inputFields = effective.filter(f => f.visibility !== 'readonly');\n return [\n ...generateRecordForModel(model.name, readFields, ctx, false, model, true),\n '',\n ...generateRecordForModel(`${model.name}Input`, inputFields, ctx, true, model, true),\n ];\n}\n\n/**\n * Bases are flattened rather than expressed as C# inheritance. A record can inherit, but a base's\n * `required` properties would then be re-declared by the override rule the contract language\n * applies, and a sealed leaf is what the serializer wants. `resolveEffectiveFields` applies the same\n * later-wins override rule the inheritance validator enforces.\n */\nfunction effectiveFieldsFor(model: ModelNode, ctx: RenderContext): FieldNode[] {\n if (!model.bases || model.bases.length === 0) return model.fields;\n const { fields, unresolved } = resolveEffectiveFields(model.name, ctx.modelIndex);\n for (const name of unresolved) {\n ctx.warn?.(`Contract '${model.name}' extends '${name}', which is not defined; its fields are missing from the generated record.`);\n }\n return fields;\n}\n\nfunction generateAliasModel(model: ModelNode, ctx: RenderContext): string[] {\n const type = model.type!;\n const inner = type.kind === 'lazy' ? type.inner : type;\n\n // A union alias is emitted by the hoisting pass, which owns the declaration named after it.\n if (ctx.hoisted?.byNode.has(inner)) return [];\n\n if (inner.kind === 'enum') return generateEnum(model.name, inner.values, ctx, model.description, model.deprecated);\n\n // An intersection or inline object at model level names a real shape, so it becomes a record\n // rather than an alias to an opaque JSON object.\n if (inner.kind === 'intersection' || inner.kind === 'inlineObject') {\n const { fields, unresolved } = resolveEffectiveFields(inner, ctx.modelIndex);\n for (const name of unresolved) {\n ctx.warn?.(`Contract '${model.name}' references '${name}', which is not defined; its fields are missing from the generated record.`);\n }\n const needsSplit = ctx.modelsWithInput.has(model.name) || fields.some(f => f.visibility !== 'normal');\n if (!needsSplit) return generateRecordForModel(model.name, fields, ctx, false, model, false);\n return [\n ...generateRecordForModel(\n model.name,\n fields.filter(f => f.visibility !== 'writeonly'),\n ctx,\n false,\n model,\n true,\n ),\n '',\n ...generateRecordForModel(\n `${model.name}Input`,\n fields.filter(f => f.visibility !== 'readonly'),\n ctx,\n true,\n model,\n true,\n ),\n ];\n }\n\n // Everything else is a name for an existing type, which C# spells as a using alias. The target\n // has to be fully qualified: a global alias is resolved without the file's own using block.\n addAlias(model.name, type, ctx, false);\n if (ctx.modelsWithInput.has(model.name)) addAlias(`${model.name}Input`, type, ctx, true);\n return [];\n}\n\n/**\n * Record one `global using X = Y;`. A nullable reference type is illegal as an alias target, so the\n * `?` is dropped and the loss reported rather than emitting a file that does not compile.\n */\nfunction addAlias(name: string, type: ContractTypeNode, ctx: RenderContext, forInput: boolean): void {\n const target = renderCSharpType(type, { ...ctx, qualify: true }, forInput);\n let aliased = target;\n if (aliased.endsWith('?') && !isNullableValueType(type, ctx)) {\n aliased = aliased.slice(0, -1);\n ctx.warn?.(\n `Contract '${name}' aliases a nullable type, which C# cannot express as a using alias; ` +\n `'${name}' is generated as '${aliased}'. Declare the nullability at each use site instead.`,\n );\n }\n const polyfilled = polyfillAliasTarget(aliased, ctx);\n if (polyfilled) {\n // A using alias has to name its target in full, which is the one place the short spelling\n // cannot do the work: `System.DateOnly` does not exist on netstandard2.0, so the alias is\n // written per framework rather than resolved by the file's imports.\n ctx.globalAliases.push(`#if NETSTANDARD2_0\\nglobal using ${name} = ${polyfilled};\\n#else\\nglobal using ${name} = ${aliased};\\n#endif`);\n return;\n }\n\n ctx.globalAliases.push(`global using ${name} = ${aliased};`);\n}\n\n/** The framework types the SDK carries a polyfill for, by their fully-qualified spelling. */\nconst POLYFILLED_TYPES: readonly string[] = ['System.DateOnly', 'System.TimeOnly'];\n\n/**\n * The netstandard2.0 spelling of an alias target, or undefined when it names no polyfilled type.\n *\n * Substring replacement rather than a lookup, because the target may be a container: `array(date)`\n * aliases to `System.Collections.Generic.List<System.DateOnly>`.\n */\nfunction polyfillAliasTarget(target: string, ctx: RenderContext): string | undefined {\n let out = target;\n for (const full of POLYFILLED_TYPES) {\n out = out.split(full).join(`${ctx.namespace}.Runtime.${full.slice('System.'.length)}`);\n }\n return out === target ? undefined : out;\n}\n\n/** Whether `type` renders as a nullable *value* type, which is a legal alias target. */\nfunction isNullableValueType(type: ContractTypeNode, ctx: RenderContext): boolean {\n const inner = type.kind === 'lazy' ? type.inner : type;\n if (inner.kind !== 'union') return false;\n const nonNull = inner.members.filter(m => !isNullScalar(m));\n if (nonNull.length !== 1) return false;\n return VALUE_TYPES.has(renderCSharpType(nonNull[0]!, { ...ctx, qualify: false }, false));\n}\n\n/** The C# spellings that are value types, so `T?` is `Nullable<T>` rather than a nullable reference. */\nconst VALUE_TYPES: ReadonlySet<string> = new Set([\n 'bool',\n 'byte',\n 'decimal',\n 'double',\n 'long',\n 'BigInteger',\n 'DateOnly',\n 'TimeOnly',\n 'DateTime',\n 'DateTimeOffset',\n 'TimeSpan',\n 'Guid',\n 'JsonElement',\n]);\n\nfunction enumMemberNames(values: string[]): Map<string, string> {\n const out = new Map<string, string>();\n const used = new Set<string>();\n for (const value of values) out.set(value, uniqueName(toCSharpEnumMemberName(value), used));\n return out;\n}\n\n/**\n * A C# enum whose members carry their wire spelling.\n *\n * `JsonStringEnumConverter<T>` plus `[JsonStringEnumMemberName]` is what makes the wire value travel\n * without a converter of the generator's own. Both are framework features, so nothing reflective is\n * generated for an enum.\n */\nfunction generateEnum(name: string, values: string[], ctx: RenderContext, description?: string, deprecated?: boolean): string[] {\n const entries = enumMemberNames(values);\n const lines: string[] = [];\n lines.push(...docLines(description, deprecated, ''));\n lines.push(`[JsonConverter(typeof(JsonStringEnumConverter<${name}>))]`);\n lines.push(`public enum ${name}`);\n lines.push('{');\n values.forEach((value, index) => {\n if (index > 0) lines.push('');\n lines.push(` [JsonStringEnumMemberName(${quoteCSharpString(value)})]`);\n lines.push(` ${entries.get(value)},`);\n });\n lines.push('}');\n // An enum has no fields, so no visibility can differ between reading and writing it.\n if (ctx.modelsWithInput.has(name)) ctx.globalAliases.push(`global using ${name}Input = ${ctx.namespace}.Models.${name};`);\n return lines;\n}\n\n/** The union interfaces a generated record has to declare it implements. */\nfunction supertypesFor(readName: string, ctx: RenderContext, forInput: boolean): string[] {\n const unions = ctx.hoisted?.memberships.get(readName) ?? [];\n return unions.map(union => {\n const decl = ctx.hoisted?.byName.get(union);\n return forInput && decl?.needsInput ? `${union}Input` : union;\n });\n}\n\nfunction generateRecordForModel(\n name: string,\n fields: FieldNode[],\n ctx: RenderContext,\n forInput: boolean,\n model: ModelNode,\n split: boolean,\n): string[] {\n const readName = forInput && name.endsWith('Input') ? name.slice(0, -'Input'.length) : name;\n const wireCase = wireCaseFor(model, forInput, split, ctx);\n // Once per model rather than once per generated record, so a split model does not say it twice.\n if (!forInput) warnUncasedNesting(model, fields, wireCase, ctx);\n return renderRecord(name, fields, ctx, forInput, supertypesFor(readName, ctx, forInput), model.description, model.deprecated, wireCase);\n}\n\nfunction renderRecord(\n name: string,\n fields: FieldNode[],\n ctx: RenderContext,\n forInput: boolean,\n supertypes: string[],\n description?: string,\n deprecated?: boolean,\n wireCase?: WireCase,\n): string[] {\n const lines: string[] = [];\n lines.push(...docLines(description, deprecated, ''));\n const implementsClause = supertypes.length > 0 ? ` : ${supertypes.join(', ')}` : '';\n\n // A contract with no visible fields still has to produce a serializable type.\n if (fields.length === 0) {\n lines.push(`public sealed record ${name}${implementsClause};`);\n return lines;\n }\n\n const memberNames = new Set(fields.map(field => memberName(field, name)));\n lines.push(`public sealed record ${name}${implementsClause}`);\n lines.push('{');\n fields.forEach((field, index) => {\n if (index > 0) lines.push('');\n lines.push(...renderField(field, ctx, forInput, name, memberNames, wireCase));\n });\n lines.push('}');\n return lines;\n}\n\n/**\n * One property.\n *\n * The `optional` and `nullable` flags are kept apart, which the Kotlin plugin cannot do: its\n * `explicitNulls = false` is one global switch, so a required-nullable null is dropped from the\n * payload along with the absent optionals. Here each property says for itself whether a null is\n * written, so `x: T | null` sends `null` and `x?: T` sends nothing.\n *\n * Every property is `required` or carries an initializer, so the record is fully assigned under\n * `#nullable enable` and the generated SDK compiles with warnings as errors. `required` is never\n * combined with `[JsonIgnore]`, which System.Text.Json rejects at run time.\n */\n/** The C# property name a field is emitted under inside `ownerTypeName`. */\nfunction memberName(field: FieldNode, ownerTypeName: string): string {\n return safeMemberName(toCSharpPropertyName(field.name), ownerTypeName);\n}\n\nfunction renderField(\n field: FieldNode,\n ctx: RenderContext,\n forInput: boolean,\n ownerTypeName: string,\n memberNames: ReadonlySet<string>,\n wireCase?: WireCase,\n): string[] {\n const propName = memberName(field, ownerTypeName);\n const wireName = applyWireCase(field.name, wireCase);\n\n let typeStr = renderCSharpType(field.type, ctx, forInput);\n if ((field.optional || field.nullable) && !typeStr.endsWith('?')) typeStr += '?';\n\n let initializer = field.default !== undefined ? renderDefault(field.default, field.type, ctx, memberNames) : undefined;\n // A `literal()` field carries exactly one value, so it defaults to it rather than being asked\n // for at every call site. The property is ordinary, so the value always reaches the wire.\n if (initializer === undefined && !field.optional && !field.nullable) {\n const inner = field.type.kind === 'lazy' ? field.type.inner : field.type;\n if (inner.kind === 'literal') initializer = renderDefault(inner.value, inner, ctx, memberNames);\n }\n\n const isRequired = !field.optional && initializer === undefined;\n\n const lines: string[] = [];\n lines.push(...docLines(field.description, field.deprecated, ' '));\n lines.push(` [JsonPropertyName(${quoteCSharpString(wireName)})]`);\n if (field.optional) lines.push(' [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]');\n const suffix = initializer !== undefined ? ` = ${initializer};` : '';\n lines.push(` public ${isRequired ? 'required ' : ''}${typeStr} ${propName} { get; init; }${suffix}`);\n return lines;\n}\n\n// ─── Hoisted declarations ──────────────────────────────────────────────────\n\n/** Emit the declaration standing in for one anonymous type, plus its Input twin when it needs one. */\nfunction generateHoisted(decl: HoistedDecl, ctx: RenderContext): string[] {\n const read = generateHoistedVariant(decl, ctx, false);\n if (!decl.needsInput) return read;\n return [...read, '', ...generateHoistedVariant(decl, ctx, true)];\n}\n\nfunction generateHoistedVariant(decl: HoistedDecl, ctx: RenderContext, forInput: boolean): string[] {\n const name = forInput ? `${decl.name}Input` : decl.name;\n switch (decl.kind) {\n case 'enum':\n return generateEnum(name, decl.values ?? [], ctx, decl.description);\n case 'record':\n return renderRecord(\n name,\n (decl.fields ?? []).filter(f => (forInput ? f.visibility !== 'readonly' : f.visibility !== 'writeonly')),\n ctx,\n forInput,\n supertypesFor(decl.name, ctx, forInput),\n decl.description,\n );\n case 'tuple':\n return generateTupleRecord(decl, name, ctx, forInput);\n case 'plainUnion':\n return generatePlainUnion(decl, name, ctx, forInput);\n case 'discriminatedUnion':\n return generateDiscriminatedUnion(decl, name, ctx, forInput);\n }\n}\n\n/** `element.Deserialize<T>(options)!`, the read expression a generated converter uses per member. */\nfunction deserializeExpr(type: ContractTypeNode, ctx: RenderContext, forInput: boolean): string {\n return `element.Deserialize<${renderCSharpType(type, ctx, forInput)}>(options)!`;\n}\n\n/**\n * A contract tuple. It travels as a JSON array, which no BCL type does: `ValueTuple` serializes as\n * an object, and a property-level `[JsonConverter]` cannot reach a tuple nested inside a `List<>`.\n * A record with a type-level converter travels correctly wherever the type appears.\n */\nfunction generateTupleRecord(decl: HoistedDecl, name: string, ctx: RenderContext, forInput: boolean): string[] {\n const items = decl.items ?? [];\n const converterName = `${name}Converter`;\n const parameters = items.map((item, index) => `${renderCSharpType(item, ctx, forInput)} Item${index}`).join(', ');\n\n const lines: string[] = [];\n lines.push(...docLines(decl.description, undefined, ''));\n lines.push(`[JsonConverter(typeof(${converterName}))]`);\n lines.push(`public sealed record ${name}(${parameters});`);\n lines.push('');\n lines.push(`/// <summary>Reads and writes <see cref=\"${name}\"/> as a JSON array.</summary>`);\n lines.push(`public sealed class ${converterName} : JsonConverter<${name}>`);\n lines.push('{');\n lines.push(` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' using var document = JsonDocument.ParseValue(ref reader);');\n lines.push(' var array = document.RootElement;');\n lines.push(` if (array.ValueKind != JsonValueKind.Array || array.GetArrayLength() != ${items.length})`);\n lines.push(' {');\n lines.push(` throw new JsonException(\"Expected a JSON array of ${items.length} elements for ${name}.\");`);\n lines.push(' }');\n lines.push('');\n lines.push(` return new ${name}(`);\n items.forEach((item, index) => {\n const expr = `array[${index}].Deserialize<${renderCSharpType(item, ctx, forInput)}>(options)!`;\n lines.push(` ${expr}${index === items.length - 1 ? '' : ','}`);\n });\n lines.push(' );');\n lines.push(' }');\n lines.push('');\n lines.push(` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' writer.WriteStartArray();');\n items.forEach((_, index) => lines.push(` JsonSerializer.Serialize(writer, value.Item${index}, options);`));\n lines.push(' writer.WriteEndArray();');\n lines.push(' }');\n lines.push('}');\n return lines;\n}\n\n/**\n * A plain `union(A | B)` becomes an abstract record with one nested member record per member, so\n * callers get a closed set to switch over instead of an untyped JSON value. The private constructor\n * is what closes it: only the nested records can derive from it.\n *\n * Decoding tries each member in declaration order and takes the first that parses, which is exactly\n * what Zod's `z.union` does on the server. Anything else would let the client and the service\n * disagree about a payload both of them accept.\n */\nfunction generatePlainUnion(decl: HoistedDecl, name: string, ctx: RenderContext, forInput: boolean): string[] {\n const converterName = `${name}Converter`;\n const members = decl.members ?? [];\n\n const lines: string[] = [];\n lines.push(...docLines(decl.description, undefined, ''));\n lines.push(`[JsonConverter(typeof(${converterName}))]`);\n lines.push(`public abstract record ${name}`);\n lines.push('{');\n lines.push(` private ${name}() { }`);\n for (const member of members) {\n lines.push('');\n lines.push(` public sealed record ${member.wrapperName}(${renderCSharpType(member.type, ctx, forInput)} Value) : ${name};`);\n }\n lines.push('}');\n lines.push('');\n lines.push(`/// <summary>Reads <see cref=\"${name}\"/> by trying each member in declaration order.</summary>`);\n lines.push(`public sealed class ${converterName} : JsonConverter<${name}>`);\n lines.push('{');\n lines.push(` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' using var document = JsonDocument.ParseValue(ref reader);');\n lines.push(' var element = document.RootElement;');\n lines.push('');\n for (const member of members) {\n lines.push(' try');\n lines.push(' {');\n lines.push(` return new ${name}.${member.wrapperName}(${deserializeExpr(member.type, ctx, forInput)});`);\n lines.push(' }');\n lines.push(' catch (JsonException)');\n lines.push(' {');\n lines.push(' // Not this member; fall through to the next.');\n lines.push(' }');\n lines.push('');\n }\n lines.push(` throw new JsonException(\"No ${name} member matched the payload.\");`);\n lines.push(' }');\n lines.push('');\n lines.push(` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' switch (value)');\n lines.push(' {');\n for (const member of members) {\n lines.push(` case ${name}.${member.wrapperName} member:`);\n lines.push(' JsonSerializer.Serialize(writer, member.Value, options);');\n lines.push(' break;');\n }\n lines.push(' default:');\n lines.push(` throw new JsonException($\"Unknown ${name} member {value.GetType().Name}.\");`);\n lines.push(' }');\n lines.push(' }');\n lines.push('}');\n return lines;\n}\n\n/**\n * A `discriminated(by=tag, A | B)` becomes an interface its member records implement, with a\n * converter that dispatches on the tag value.\n *\n * An interface rather than an abstract base record: a record has single inheritance, and the\n * hoisting pass allows one contract to belong to several unions. It is also why the tag stays a real\n * property on each member rather than becoming `[JsonPolymorphic]` metadata, which System.Text.Json\n * refuses to pair with a property of the same name.\n */\nfunction generateDiscriminatedUnion(decl: HoistedDecl, name: string, ctx: RenderContext, forInput: boolean): string[] {\n const converterName = `${name}Converter`;\n const members = (decl.members ?? []).map(member => ({ ...member, recordName: memberRecordName(member.typeName, ctx, forInput) }));\n const discriminator = decl.discriminator ?? '';\n\n const lines: string[] = [];\n lines.push(...docLines(decl.description, undefined, ''));\n lines.push(`[JsonConverter(typeof(${converterName}))]`);\n lines.push(`public interface ${name}`);\n lines.push('{');\n lines.push('}');\n lines.push('');\n lines.push(`/// <summary>Reads <see cref=\"${name}\"/> by dispatching on its '${discriminator}' tag.</summary>`);\n lines.push(`public sealed class ${converterName} : JsonConverter<${name}>`);\n lines.push('{');\n lines.push(` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' using var document = JsonDocument.ParseValue(ref reader);');\n lines.push(' var element = document.RootElement;');\n lines.push(\n ` var tag = element.TryGetProperty(${quoteCSharpString(discriminator)}, out var tagElement) && tagElement.ValueKind == JsonValueKind.String`,\n );\n lines.push(' ? tagElement.GetString()');\n lines.push(' : null;');\n lines.push('');\n lines.push(' return tag switch');\n lines.push(' {');\n for (const member of members) {\n lines.push(` ${quoteCSharpString(member.tag ?? '')} => element.Deserialize<${member.recordName}>(options)!,`);\n }\n lines.push(` _ => throw new JsonException($\"Unknown ${name} ${discriminator}: {tag}\"),`);\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n lines.push(` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`);\n lines.push(' {');\n lines.push(' switch (value)');\n lines.push(' {');\n for (const member of members) {\n lines.push(` case ${member.recordName} member:`);\n lines.push(' JsonSerializer.Serialize(writer, member, options);');\n lines.push(' break;');\n }\n lines.push(' default:');\n lines.push(` throw new JsonException($\"Unknown ${name} member {value.GetType().Name}.\");`);\n lines.push(' }');\n lines.push(' }');\n lines.push('}');\n return lines;\n}\n\n/** The concrete record name of a union member, in the read or input variant. */\nfunction memberRecordName(typeName: string, ctx: RenderContext, forInput: boolean): string {\n if (!forInput) return typeName;\n const decl = ctx.hoisted?.byName.get(typeName);\n if (decl) return decl.needsInput ? `${typeName}Input` : typeName;\n return ctx.modelsWithInput.has(typeName) ? `${typeName}Input` : typeName;\n}\n\n// ─── Shared helpers ────────────────────────────────────────────────────────\n\n/**\n * XML doc for a declaration. Deprecation is a `<remarks>` line rather than `[Obsolete]`: an obsolete\n * model would raise CS0618 in every generated converter and client that names it, which the\n * compile check treats as an error. Operations, which nothing generated calls, do get `[Obsolete]`.\n */\nfunction docLines(description: string | undefined, deprecated: boolean | undefined, indent: string): string[] {\n const lines: string[] = [];\n if (description) lines.push(...xmlDocLines(description, indent));\n if (deprecated) lines.push(...xmlDocLines('Deprecated in the contract.', indent, 'remarks'));\n return lines;\n}\n\nfunction uniqueName(name: string, used: Set<string>): string {\n if (!used.has(name)) {\n used.add(name);\n return name;\n }\n let n = 2;\n while (used.has(`${name}${n}`)) n++;\n used.add(`${name}${n}`);\n return `${name}${n}`;\n}\n\nexport type { RenderContext };\n","/**\n * Identifier and file-name conversions for C# output.\n *\n * Kept separate from the codegen modules because both the model and the client generators need the\n * same conversions, and a mismatch between them would produce a client that references a property\n * name the model never declared.\n */\n\n/**\n * C#'s reserved keywords — illegal as bare identifiers anywhere, so a name that collides with one\n * has to be escaped with `@`. Contextual keywords (`record`, `required`, `init`, `value`, `var`,\n * `async`, `await`, `yield`, `nameof`, `when`) are legal identifiers and are deliberately absent:\n * escaping them would only make the generated code noisier.\n */\nexport const CSHARP_KEYWORDS: ReadonlySet<string> = new Set([\n 'abstract',\n 'as',\n 'base',\n 'bool',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'checked',\n 'class',\n 'const',\n 'continue',\n 'decimal',\n 'default',\n 'delegate',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'event',\n 'explicit',\n 'extern',\n 'false',\n 'finally',\n 'fixed',\n 'float',\n 'for',\n 'foreach',\n 'goto',\n 'if',\n 'implicit',\n 'in',\n 'int',\n 'interface',\n 'internal',\n 'is',\n 'lock',\n 'long',\n 'namespace',\n 'new',\n 'null',\n 'object',\n 'operator',\n 'out',\n 'override',\n 'params',\n 'private',\n 'protected',\n 'public',\n 'readonly',\n 'ref',\n 'return',\n 'sbyte',\n 'sealed',\n 'short',\n 'sizeof',\n 'stackalloc',\n 'static',\n 'string',\n 'struct',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'uint',\n 'ulong',\n 'unchecked',\n 'unsafe',\n 'ushort',\n 'using',\n 'virtual',\n 'void',\n 'volatile',\n 'while',\n]);\n\n/**\n * Members the C# compiler already declares on a record, plus the ones a record's synthesized\n * members would collide with. A contract field landing on any of these has to be renamed.\n */\nconst RESERVED_MEMBER_NAMES: ReadonlySet<string> = new Set(['Equals', 'GetHashCode', 'GetType', 'ToString', 'EqualityContract', 'PrintMembers']);\n\n/**\n * Prefix `name` with `@` when it is a C# keyword, so it can still be used as a parameter or local.\n * The `@` is a lexical escape only: the identifier is still spelled `name` everywhere it matters,\n * including in `nameof` and in reflection, so nothing downstream has to know about it.\n */\nexport function escapeCSharpIdentifier(name: string): string {\n return CSHARP_KEYWORDS.has(name) ? `@${name}` : name;\n}\n\n/**\n * Convert a contract field name to a C# property name in PascalCase.\n *\n * Separators (`-`, `_`, `.`, spaces) introduce a word boundary and are dropped, so `x-request-id`\n * becomes `XRequestId`. A leading digit gets an underscore prefix, since C# identifiers cannot\n * start with one. No keyword escaping is needed: every C# keyword is lowercase and this always\n * produces an initial capital.\n *\n * The original name is preserved on the wire through `[JsonPropertyName]`, so this conversion is\n * free to be lossy as long as it is deterministic.\n */\nexport function toCSharpPropertyName(name: string): string {\n const words = splitWords(name);\n if (words.length === 0) return '_';\n let result = words.map(capitalize).join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Convert a contract parameter or path placeholder to a C# parameter name in camelCase:\n * `invoice-id` becomes `invoiceId`. Keyword-escaped, because camelCase lands on keywords\n * regularly — a path parameter named `event` or `params` is ordinary in a contract.\n */\nexport function toCSharpParameterName(name: string): string {\n const words = splitWords(name);\n if (words.length === 0) return '_';\n const head = words[0]!.toLowerCase();\n const rest = words.slice(1).map(capitalize);\n let result = head + rest.join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return escapeCSharpIdentifier(result);\n}\n\n/**\n * A C# parameter or local name for each declared name, keyed by that name.\n *\n * Each goes through {@link toCSharpParameterName}, then gains a `_` until it collides with neither\n * one of `taken` nor another name's result, and is keyword-escaped last. The comparison is on the\n * unescaped spelling, since `@class` and `class` are the same identifier to the compiler. Returns\n * the plain conversion in the common case, so existing output stays byte-identical.\n *\n * @param taken Unescaped identifiers the surrounding generated code already binds or reads, which\n * a declared name must not duplicate or shadow.\n */\nexport function bindCSharpParameterNames(names: readonly string[], taken: Iterable<string>): Map<string, string> {\n const unavailable = new Set<string>(taken);\n const bindings = new Map<string, string>();\n for (const name of names) {\n let local = toCSharpParameterName(name).replace(/^@/, '');\n while (unavailable.has(local)) local += '_';\n unavailable.add(local);\n bindings.set(name, escapeCSharpIdentifier(local));\n }\n return bindings;\n}\n\n/**\n * Make a property name safe inside `ownerTypeName`.\n *\n * C# rejects a member whose name matches its enclosing type (CS0542), which a contract hits\n * whenever a model has a field of its own name — `contract Invoice { invoice: ... }`. A record also\n * synthesizes members that a contract field can collide with. Both are resolved by appending\n * `Value`; the wire name is unaffected, since `[JsonPropertyName]` is always emitted.\n */\nexport function safeMemberName(propertyName: string, ownerTypeName: string): string {\n if (propertyName === ownerTypeName || RESERVED_MEMBER_NAMES.has(propertyName)) return `${propertyName}Value`;\n return propertyName;\n}\n\n/**\n * Convert a name to a C# type name in PascalCase. Never escaped: type names are generated (from\n * model names, method names, or status codes) rather than taken verbatim, so a collision with a\n * keyword is a naming bug worth surfacing rather than papering over.\n */\nexport function toCSharpTypeName(name: string): string {\n const words = splitWords(name);\n if (words.length === 0) return '_';\n let result = words.map(capitalize).join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Make an already-composed name safe to use as a C# type name, without re-casing it.\n *\n * Distinct from {@link toCSharpTypeName}, which splits a source name into words and rebuilds it:\n * running that over a name already assembled from PascalCase parts would fold `MV` back to `Mv`.\n */\nexport function sanitizeCSharpTypeName(name: string): string {\n let result = name.replace(/[^a-zA-Z0-9]/g, '');\n if (result.length === 0) return '_';\n result = result.charAt(0).toUpperCase() + result.slice(1);\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Convert an enum member value to a C# enum member name in PascalCase: `in-progress` becomes\n * `InProgress`. The value itself always travels via `[JsonStringEnumMemberName]`, so this only has\n * to be a stable identifier.\n */\nexport function toCSharpEnumMemberName(value: string): string {\n const words = splitWords(value);\n if (words.length === 0) return '_';\n let result = words.map(capitalize).join('');\n if (/^\\d/.test(result)) result = `_${result}`;\n return result;\n}\n\n/**\n * Derive the PascalCase base used for a generated file's names from a `.ck` file path:\n * `\"ledger.categories.ck\"` becomes `\"LedgerCategories\"`. Both the models file and the client class\n * for one source file are named from this, so they stay visibly paired in the output tree.\n */\nexport function deriveCSharpFileBase(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op\\.)?ck$/, '') ?? 'models';\n return toCSharpTypeName(base);\n}\n\n/**\n * Render `text` as an XML doc comment indented by `indent`, wrapped in `tag`. Returns `[]` for\n * empty text so callers can splat unconditionally.\n *\n * `///` is a line comment, so unlike Kotlin's KDoc there is no delimiter to break out of. What does\n * have to be handled is XML: an unescaped `&` or `<` in a description makes the doc file malformed,\n * which the compiler reports as a warning and `-warnaserror` turns into a build failure.\n */\nexport function xmlDocLines(text: string, indent: string, tag = 'summary'): string[] {\n if (text.length === 0) return [];\n const safe = escapeXml(text);\n const sourceLines = safe.split('\\n');\n if (sourceLines.length === 1) return [`${indent}/// <${tag}>${sourceLines[0]}</${tag}>`];\n return [`${indent}/// <${tag}>`, ...sourceLines.map(line => `${indent}/// ${line}`.trimEnd()), `${indent}/// </${tag}>`];\n}\n\n/** Escape the three characters that would otherwise make a doc comment malformed XML. */\nexport function escapeXml(text: string): string {\n return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n/**\n * Render `value` as a C# string literal. No `$` handling: interpolated strings are the only place\n * `$` is special, and no generated literal built from contract text is interpolated.\n */\nexport function quoteCSharpString(value: string): string {\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\0/g, '\\\\0');\n return `\"${escaped}\"`;\n}\n\n/**\n * Split an identifier into words on separators and camelCase boundaries.\n * `\"x-request-id\"` becomes `[\"x\", \"request\", \"id\"]`; `\"createdAt\"` becomes `[\"created\", \"At\"]`;\n * `\"myHTTPClient\"` becomes `[\"my\", \"HTTP\", \"Client\"]`.\n */\nfunction splitWords(name: string): string[] {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\n}\n\nfunction capitalize(word: string): string {\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n}\n","import type {\n ModelNode,\n OpOperationNode,\n OpResponseBodyNode,\n OpResponseHeaderNode,\n OpResponseNode,\n OpRootNode,\n OpRouteNode,\n ParamSource,\n} from '@contractkit/core';\nimport { classifyContentType, observableResponses, resolveModifiers } from '@contractkit/core';\nimport type { HoistResult } from './hoist.js';\nimport { createRenderContext, renderCSharpType, renderFile, type CSharpDateTypes, type RenderContext } from './codegen-models.js';\nimport {\n bindCSharpParameterNames,\n deriveCSharpFileBase,\n quoteCSharpString,\n safeMemberName,\n toCSharpParameterName,\n toCSharpPropertyName,\n toCSharpTypeName,\n xmlDocLines,\n} from './naming.js';\n\nexport interface CSharpClientCodegenOptions {\n namespace: string;\n /** Which C# type a `date` maps to (default: `dateonly`). Applies to response headers too. */\n dateTypes?: CSharpDateTypes;\n modelsWithInput: ReadonlySet<string>;\n modelIndex?: ReadonlyMap<string, ModelNode>;\n hoisted?: HoistResult;\n includeInternal?: boolean;\n warn?: (message: string) => void;\n}\n\n/**\n * The `using` block every generated client file carries. Fixed for the same reason the models\n * block is: everything a client can name is in the base class library or in the SDK's own two\n * namespaces.\n */\nfunction clientUsings(namespaceName: string): string[] {\n return [\n 'using System;',\n 'using System.Collections.Generic;',\n 'using System.Globalization;',\n 'using System.Net.Http;',\n 'using System.Numerics;',\n 'using System.Text.Json;',\n 'using System.Text.Json.Serialization;',\n 'using System.Threading;',\n 'using System.Threading.Tasks;',\n 'using System.Xml;',\n `using ${namespaceName}.Models;`,\n `using ${namespaceName}.Runtime;`,\n ];\n}\n\n/** Whether the root has at least one operation eligible for client emission. */\nexport function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;\n }\n }\n return false;\n}\n\nexport function deriveClientClassName(file: string): string {\n return `${deriveCSharpFileBase(file)}Client`;\n}\n\nexport function deriveClientPropertyName(file: string): string {\n return deriveCSharpFileBase(file);\n}\n\n/**\n * Generate the client class for one operations file: one `Task`-returning method per public\n * operation, plus the request and response shapes those methods name.\n */\nexport function generateCSharpClient(root: OpRootNode, opts: CSharpClientCodegenOptions): string {\n const className = deriveClientClassName(root.file);\n const includeInternal = opts.includeInternal ?? false;\n const ctx = createRenderContext(opts);\n\n const publicOps: { route: OpRouteNode; op: OpOperationNode }[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n publicOps.push({ route, op });\n }\n }\n\n // Request and response shapes, emitted after the class: a method's signature names them, and C#\n // does not care about declaration order.\n const shapeLines: string[] = [];\n for (const { route, op } of publicOps) {\n const base = methodBase(deriveMethodName(op, route));\n for (const { source, suffix } of [\n { source: op.query, suffix: 'Query' },\n { source: op.headers, suffix: 'Headers' },\n ]) {\n if (source?.kind !== 'params' || source.nodes.length === 0) continue;\n const shapeName = `${base}${suffix}`;\n shapeLines.push('');\n shapeLines.push(\n ...xmlDocLines(`The ${suffix === 'Query' ? 'query parameters' : 'request headers'} declared on ${where(route, op)}.`, ''),\n );\n shapeLines.push(`public sealed record ${shapeName}`);\n shapeLines.push('{');\n source.nodes.forEach((node, index) => {\n if (index > 0) shapeLines.push('');\n const propName = safeMemberName(toCSharpPropertyName(node.name), shapeName);\n let type = renderCSharpType(node.type, ctx, true);\n const optional = Boolean(node.optional) || node.default !== undefined;\n if (optional && !type.endsWith('?')) type += '?';\n shapeLines.push(` [JsonPropertyName(${quoteCSharpString(node.name)})]`);\n if (optional) shapeLines.push(' [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]');\n shapeLines.push(` public ${optional ? '' : 'required '}${type} ${propName} { get; init; }`);\n });\n shapeLines.push('}');\n }\n shapeLines.push(...responseDeclarations(route, op, ctx));\n }\n\n const methodLines: string[] = [];\n const seen = new Map<string, string>();\n for (const { route, op } of publicOps) {\n const methodName = deriveMethodName(op, route);\n const clash = seen.get(methodName);\n if (clash) {\n throw new Error(\n `plugin-csharp: ${where(route, op)} and ${clash} both generate the client method '${methodName}' on ${className}. ` +\n `Give one of them a distinct 'sdk:' name.`,\n );\n }\n seen.set(methodName, where(route, op));\n methodLines.push('');\n methodLines.push(...generateMethod(route, op, ctx, methodName));\n }\n\n const body: string[] = [];\n body.push('');\n // The basename, not `root.file`: that is an absolute path on whoever ran the build, and\n // embedding it would make the generated source differ between machines.\n body.push(...xmlDocLines(`Operations declared in <c>${root.file.split('/').pop()}</c>.`, ''));\n body.push(`public sealed class ${className}(SdkHttp http)`);\n body.push('{');\n // `methodLines` opens with a blank separator between methods; the first one sits against the\n // class header, so it is dropped rather than left as a gap.\n body.push(...methodLines.slice(1).map(l => (l === '' ? '' : ` ${l}`)));\n body.push('}');\n body.push(...shapeLines);\n\n return renderFile(`${opts.namespace}.Clients`, ctx.globalAliases, clientUsings(opts.namespace), body);\n}\n\nfunction where(route: OpRouteNode, op: OpOperationNode): string {\n return `${op.method.toUpperCase()} ${route.path}`;\n}\n\n/** The PascalCase stem generated type names hang off: the method name without its `Async` suffix. */\nfunction methodBase(methodName: string): string {\n return methodName.endsWith('Async') ? methodName.slice(0, -'Async'.length) : methodName;\n}\n\n// ─── Response shape ────────────────────────────────────────────────────────\n\n/**\n * How a method reports what came back, mirroring the TypeScript, Python and Kotlin SDKs.\n *\n * `simple` is the overwhelmingly common case and returns the body itself. The other two exist\n * because the caller cannot otherwise tell which status, or which mime, it received.\n */\ntype ResponseShape =\n | { kind: 'simple'; response?: OpResponseNode }\n | { kind: 'multiMime'; response: OpResponseNode }\n | { kind: 'multiStatus'; responses: OpResponseNode[] };\n\nfunction responseShape(op: OpOperationNode): ResponseShape {\n // `observableResponses` is shared with the router and the other SDKs, so all of them agree on\n // which statuses are values and which are failures.\n const observable = observableResponses(op);\n if (observable.length > 1) return { kind: 'multiStatus', responses: observable };\n const response = observable[0];\n if (response && response.bodies.length > 1) return { kind: 'multiMime', response };\n return { kind: 'simple', response };\n}\n\nfunction observableOf(shape: ResponseShape): OpResponseNode[] {\n if (shape.kind === 'multiStatus') return shape.responses;\n return shape.response ? [shape.response] : [];\n}\n\n// ─── Method generation ─────────────────────────────────────────────────────\n\nfunction generateMethod(route: OpRouteNode, op: OpOperationNode, ctx: RenderContext, methodName: string): string[] {\n const base = methodBase(methodName);\n const shape = responseShape(op);\n const returnType = returnTypeFor(shape, op, base, ctx);\n const observable = observableOf(shape);\n const expectStatuses = observable.filter(r => r.statusCode < 200 || r.statusCode >= 300).map(r => r.statusCode);\n\n const pathBindings = bindPathParams(route);\n const params = buildMethodParams(route, op, ctx, pathBindings);\n // Everything the body can see by name: a response-header pattern variable must not redeclare one.\n const bound = [...METHOD_LOCALS, ...params.map(p => p.name.replace(/^@/, ''))];\n const signature = [...params.map(p => `${p.type} ${p.name}${p.optional ? ' = null' : ''}`), 'CancellationToken cancellationToken = default'].join(\n ', ',\n );\n\n const lines: string[] = [];\n lines.push(...methodDoc(route, op, observable));\n if (resolveModifiers(route, op).includes('deprecated')) lines.push('[Obsolete(\"Deprecated in the contract\")]');\n\n lines.push(`public async ${returnType === 'void' ? 'Task' : `Task<${returnType}>`} ${methodName}(${signature})`);\n lines.push('{');\n\n const callArgs: string[] = [httpMethodExpression(op.method), buildPathExpression(route.path, route.params, pathBindings)];\n if (op.query) callArgs.push('query: http.Params(query)');\n if (op.headers) callArgs.push('headers: http.Params(customHeaders)');\n const content = bodyArgument(op);\n if (content) callArgs.push(content);\n if (expectStatuses.length > 0) callArgs.push(`expectStatuses: new[] { ${expectStatuses.join(', ')} }`);\n callArgs.push('cancellationToken: cancellationToken');\n\n const assignment = returnType === 'void' ? 'await ' : 'var response = await ';\n lines.push(` ${assignment}http.ExecuteAsync(`);\n callArgs.forEach((arg, index) => {\n lines.push(` ${arg}${index === callArgs.length - 1 ? ').ConfigureAwait(false);' : ','}`);\n });\n lines.push(...returnStatements(shape, op, base, ctx, where(route, op), bound));\n lines.push('}');\n return lines;\n}\n\n/** What a method hands back. Declared before the body so the two cannot drift apart. */\nfunction returnTypeFor(shape: ResponseShape, op: OpOperationNode, base: string, ctx: RenderContext): string {\n if (shape.kind !== 'simple') return `${base}Response`;\n const response = shape.response;\n const body = response?.bodies[0];\n const headers = response?.headers ?? [];\n if (!body) return headers.length > 0 ? headersRecordName(op, base) : 'void';\n const dataType = bodyCSharpType(body, ctx);\n // A declared response header changes the return shape: the body alone cannot carry it.\n return headers.length > 0 ? `${base}Result` : dataType;\n}\n\n/** The C# type of one response body. A non-JSON mime ignores the schema, as in every SDK. */\nfunction bodyCSharpType(body: OpResponseBodyNode, ctx: RenderContext): string {\n switch (classifyContentType(body.contentType)) {\n case 'text':\n return 'string';\n case 'binary':\n return 'byte[]';\n default:\n return renderCSharpType(body.bodyType, ctx, false);\n }\n}\n\n/** The expression that reads one body out of the response. */\nfunction bodyReadExpr(body: OpResponseBodyNode, ctx: RenderContext): string {\n switch (classifyContentType(body.contentType)) {\n case 'text':\n return 'response.Text';\n case 'binary':\n return 'response.Bytes';\n default:\n return `http.ReadJson<${renderCSharpType(body.bodyType, ctx, false)}>(response)`;\n }\n}\n\n/** The statements after `ExecuteAsync`, which turn the response into the declared return type. */\nfunction returnStatements(\n shape: ResponseShape,\n op: OpOperationNode,\n base: string,\n ctx: RenderContext,\n place: string,\n bound: readonly string[],\n): string[] {\n if (shape.kind === 'simple') {\n const response = shape.response;\n const body = response?.bodies[0];\n const headers = response?.headers ?? [];\n if (headers.length === 0) return body ? [` return ${bodyReadExpr(body, ctx)};`] : [];\n const lines = readHeaderLines(headers, headersRecordName(op, base), ctx, place, ' ', bound);\n return body ? [...lines, ` return new ${base}Result(${bodyReadExpr(body, ctx)}, headers);`] : [...lines, ' return headers;'];\n }\n\n if (shape.kind === 'multiMime') {\n const headers = shape.response.headers ?? [];\n const lines = headers.length > 0 ? readHeaderLines(headers, headersRecordName(op, base), ctx, place, ' ', bound) : [];\n lines.push(...mimeSwitch(shape.response, base, undefined, ctx, ' ', headers.length > 0));\n return lines;\n }\n\n // The first declared status is the fall-through, so the switch is exhaustive without a branch\n // for a status the service cannot return.\n const [fallback, ...rest] = shape.responses;\n const lines: string[] = [' switch (response.Status)', ' {'];\n for (const response of rest) {\n lines.push(` case ${response.statusCode}:`);\n lines.push(' {');\n lines.push(...statusBranch(response, op, base, response.statusCode, ctx, place, ' ', bound));\n lines.push(' }');\n lines.push('');\n }\n lines.push(' default:');\n lines.push(' {');\n lines.push(...statusBranch(fallback!, op, base, fallback!.statusCode, ctx, place, ' ', bound));\n lines.push(' }');\n lines.push(' }');\n return lines;\n}\n\n/**\n * One switch branch: read this status's headers, then dispatch over its mimes.\n *\n * Every branch is braced. Two branches each declaring `headers` would otherwise collide, since a\n * declaration in a switch section is scoped to the whole switch block rather than to its own case.\n */\nfunction statusBranch(\n response: OpResponseNode,\n op: OpOperationNode,\n base: string,\n statusCode: number,\n ctx: RenderContext,\n place: string,\n indent: string,\n bound: readonly string[],\n): string[] {\n const lines: string[] = [];\n const headers = response.headers ?? [];\n if (headers.length > 0) lines.push(...readHeaderLines(headers, headersRecordName(op, base, statusCode), ctx, place, indent, bound));\n lines.push(...mimeSwitch(response, base, statusCode, ctx, indent, headers.length > 0));\n return lines;\n}\n\n/**\n * Construct the response case, dispatching on the content type when a status declares several\n * mimes. The first declared mime is the fall-through, for the same reason the first status is.\n */\nfunction mimeSwitch(\n response: OpResponseNode,\n base: string,\n statusCode: number | undefined,\n ctx: RenderContext,\n indent: string,\n hasHeaders: boolean,\n): string[] {\n const bodies = response.bodies;\n const construct = (body: OpResponseBodyNode | undefined): string => {\n const args: string[] = [];\n if (body) args.push(bodyReadExpr(body, ctx));\n if (hasHeaders) args.push('headers');\n return `new ${base}Response.${leafRecordName(response, body, statusCode)}(${args.join(', ')})`;\n };\n\n if (bodies.length <= 1) return [`${indent}return ${construct(bodies[0])};`];\n\n const [fallback, ...rest] = bodies;\n const lines: string[] = [`${indent}switch (response.ContentType)`, `${indent}{`];\n for (const body of rest) {\n lines.push(`${indent} case ${quoteCSharpString(body.contentType)}:`);\n lines.push(`${indent} return ${construct(body)};`);\n }\n lines.push(`${indent} default:`);\n lines.push(`${indent} return ${construct(fallback!)};`);\n lines.push(`${indent}}`);\n return lines;\n}\n\n/** The `content:` argument for the request body, if the operation declares one. */\nfunction bodyArgument(op: OpOperationNode): string | undefined {\n // Only the first declared mime is used, matching the Python and Kotlin SDKs: a method has one\n // signature, and the alternatives describe the same payload in a different encoding.\n const body = op.request?.bodies[0];\n if (!body) return undefined;\n const mime = quoteCSharpString(body.contentType);\n switch (classifyContentType(body.contentType)) {\n case 'multipart':\n return 'content: http.MultipartContent(body)';\n case 'urlencoded':\n return 'content: http.FormContent(body)';\n case 'text':\n return `content: http.TextContent(body, ${mime})`;\n case 'binary':\n return `content: http.BinaryContent(body, ${mime})`;\n default:\n return `content: http.JsonContent(body, ${mime})`;\n }\n}\n\n// ─── Response declarations ─────────────────────────────────────────────────\n\n/**\n * The name of a response-headers record: `<Method><Status>Headers` when the status is part of the\n * value, otherwise `<Method>Headers`.\n *\n * The request-headers record claims `<Method>Headers` first, since it is the one a caller builds by\n * name, so an operation that declares both gets `<Method>ResponseHeaders` for its response side.\n * Two records of one name in one namespace is CS0101.\n */\nfunction headersRecordName(op: OpOperationNode, base: string, statusCode?: number): string {\n if (statusCode !== undefined) return `${base}${statusCode}Headers`;\n return declaresRequestHeadersRecord(op) ? `${base}ResponseHeaders` : `${base}Headers`;\n}\n\n/** Whether the operation's `headers:` block gets a generated `<Method>Headers` record. */\nfunction declaresRequestHeadersRecord(op: OpOperationNode): boolean {\n return op.headers?.kind === 'params' && op.headers.nodes.length > 0;\n}\n\n/**\n * The name of one leaf of a method's response union.\n *\n * Leaves are flat rather than nested per status, so a caller switches in one level. A status with\n * several mimes gets one leaf per mime, keeping the mime and the body type it decodes to\n * correlated.\n */\nfunction leafRecordName(response: OpResponseNode, body: OpResponseBodyNode | undefined, statusCode: number | undefined): string {\n const statusPart = statusCode === undefined ? '' : `Status${statusCode}`;\n if (response.bodies.length <= 1 || !body) return statusPart || 'Body';\n return `${statusPart}${toCSharpTypeName(body.contentType.replace(/[+/.]/g, ' '))}`;\n}\n\n/**\n * The `<Method>Headers`, `<Method>Result` and `<Method>Response` declarations a method's return\n * type names. Emitted alongside the client class, since they belong to one method each.\n */\nfunction responseDeclarations(route: OpRouteNode, op: OpOperationNode, ctx: RenderContext): string[] {\n const shape = responseShape(op);\n const base = methodBase(deriveMethodName(op, route));\n const place = where(route, op);\n const lines: string[] = [];\n\n const headerRecord = (headers: OpResponseHeaderNode[], name: string): void => {\n const parameters = headers\n .map(header => {\n const reader = headerReader(header, place, ctx.dateTypes);\n const type = header.optional ? `${reader.type}?` : reader.type;\n return `${type} ${safeMemberName(toCSharpPropertyName(header.name), name)}`;\n })\n .join(', ');\n lines.push('');\n lines.push(...xmlDocLines(`Response headers declared on ${place}.`, ''));\n lines.push(`public sealed record ${name}(${parameters});`);\n };\n\n if (shape.kind === 'simple') {\n const response = shape.response;\n const headers = response?.headers ?? [];\n if (headers.length === 0) return lines;\n headerRecord(headers, headersRecordName(op, base));\n const body = response?.bodies[0];\n if (body) {\n lines.push('');\n lines.push(...xmlDocLines(`The body of ${place}, with the response headers the contract declares.`, ''));\n lines.push(`public sealed record ${base}Result(${bodyCSharpType(body, ctx)} Data, ${headersRecordName(op, base)} Headers);`);\n }\n return lines;\n }\n\n const responses = observableOf(shape);\n const withStatus = shape.kind === 'multiStatus';\n for (const response of responses) {\n const headers = response.headers ?? [];\n if (headers.length > 0) headerRecord(headers, headersRecordName(op, base, withStatus ? response.statusCode : undefined));\n }\n\n lines.push('');\n lines.push(\n ...xmlDocLines(\n `What ${place} returned.\\n\\n` +\n (withStatus\n ? 'The operation declares several statuses the service produces, so the status is part of the value.'\n : 'The status declares several content types, so which one arrived is part of the value.'),\n '',\n ),\n );\n lines.push(`public abstract record ${base}Response`);\n lines.push('{');\n lines.push(` private ${base}Response() { }`);\n for (const response of responses) {\n const statusCode = withStatus ? response.statusCode : undefined;\n const headers = response.headers ?? [];\n const bodies = response.bodies.length > 0 ? response.bodies : [undefined];\n for (const body of bodies) {\n const name = leafRecordName(response, body, statusCode);\n const parameters: string[] = [];\n if (body) parameters.push(`${bodyCSharpType(body, ctx)} Data`);\n if (headers.length > 0) parameters.push(`${headersRecordName(op, base, statusCode)} Headers`);\n lines.push('');\n lines.push(` public sealed record ${name}(${parameters.join(', ')}) : ${base}Response;`);\n }\n }\n lines.push('}');\n return lines;\n}\n\n/**\n * The C# type of a response header, and how to turn the raw string into it.\n *\n * Header values arrive as text, so the declared type is what the caller gets and the conversion\n * happens here. The accepted set mirrors the other SDKs; anything else is rejected at build time\n * rather than silently handed back as a string.\n *\n * @throws {Error} When the header's declared type cannot be read from an HTTP header.\n */\nfunction headerReader(header: OpResponseHeaderNode, place: string, dateTypes: CSharpDateTypes): { type: string; read: (raw: string) => string } {\n const scalar = header.type.kind === 'scalar' ? header.type.name : undefined;\n switch (scalar) {\n case 'string':\n case 'email':\n case 'url':\n case 'interval':\n case 'unknown':\n return { type: 'string', read: raw => raw };\n case 'number':\n return { type: 'double', read: raw => `double.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'int':\n return { type: 'long', read: raw => `long.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'bigint':\n return { type: 'BigInteger', read: raw => `BigInteger.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'boolean':\n return { type: 'bool', read: raw => `${raw} == \"true\"` };\n case 'uuid':\n return { type: 'Guid', read: raw => `Guid.Parse(${raw})` };\n case 'date':\n return dateTypes === 'datetime'\n ? { type: 'DateTime', read: raw => `DateTime.Parse(${raw}, CultureInfo.InvariantCulture)` }\n : { type: 'DateOnly', read: raw => `DateOnly.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'time':\n return { type: 'TimeOnly', read: raw => `TimeOnly.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'datetime':\n return { type: 'DateTimeOffset', read: raw => `DateTimeOffset.Parse(${raw}, CultureInfo.InvariantCulture)` };\n case 'duration':\n return { type: 'TimeSpan', read: raw => `XmlConvert.ToTimeSpan(${raw})` };\n default:\n throw new Error(\n `plugin-csharp: response header '${header.name}' on ${place} is declared as ${describeHeaderType(header.type)}, ` +\n `which cannot be read from an HTTP header. Header values arrive as strings — declare it as string, email, url, uuid, ` +\n `date, time, datetime, duration, interval, int, number, boolean or bigint.`,\n );\n }\n}\n\n/** A short, contract-facing description of a header type, for the rejection above. */\nfunction describeHeaderType(type: { kind: string; name?: string }): string {\n if (type.kind === 'scalar') return `the '${type.name}' scalar`;\n if (type.kind === 'ref') return `the contract '${type.name}'`;\n return `${type.kind === 'array' || type.kind === 'inlineObject' ? 'an' : 'a'} ${type.kind}`;\n}\n\n/** The lines that build one response-headers value out of the response. */\nfunction readHeaderLines(\n headers: OpResponseHeaderNode[],\n typeName: string,\n ctx: RenderContext,\n place: string,\n indent: string,\n bound: readonly string[],\n): string[] {\n // Pattern variables share the statement's scope, and the method's: each needs a name nothing\n // else in either binds.\n const locals = bindCSharpParameterNames(\n headers.filter(h => h.optional).map(h => h.name),\n bound,\n );\n const args = headers.map(header => {\n const reader = headerReader(header, place, ctx.dateTypes);\n const name = quoteCSharpString(header.name);\n // A required header the service omitted is a broken contract, not a null the caller has to\n // handle; an optional one simply stays absent.\n if (!header.optional) return reader.read(`http.RequireHeader(response, ${name})`);\n const local = locals.get(header.name)!;\n return `response.Header(${name}) is { } ${local} ? ${reader.read(local)} : null`;\n });\n const lines: string[] = [`${indent}var headers = new ${typeName}(`];\n args.forEach((arg, index) => lines.push(`${indent} ${arg}${index === args.length - 1 ? ');' : ','}`));\n return lines;\n}\n\nfunction methodDoc(route: OpRouteNode, op: OpOperationNode, observable: OpResponseNode[]): string[] {\n const lines: string[] = [];\n const parts: string[] = [];\n if (op.name) parts.push(op.name);\n const description = op.description ?? route.description;\n if (description) parts.push(description);\n if (parts.length > 0) lines.push(...xmlDocLines(parts.join('\\n'), ''));\n\n const thrown = op.responses.filter(r => !observable.includes(r)).map(r => r.statusCode);\n if (thrown.length > 0) lines.push(`/// <exception cref=\"SdkException\">On ${thrown.join(', ')}.</exception>`);\n return lines;\n}\n\n/**\n * How a verb is spelled at the call site.\n *\n * `System.Net.Http.HttpMethod` carries a static for every verb the grammar allows except PATCH,\n * which netstandard2.0 does not have, so PATCH goes through the runtime's own `SdkHttp.Patch`.\n */\nfunction httpMethodExpression(method: string): string {\n const lower = method.toLowerCase();\n if (lower === 'patch') return 'SdkHttp.Patch';\n return `HttpMethod.${lower.charAt(0).toUpperCase()}${lower.slice(1)}`;\n}\n\n// ─── Path building ─────────────────────────────────────────────────────────\n\n/**\n * Placeholder names as the `.ck` grammar allows them: `-` and `.` are legal inside one, so a\n * narrower pattern would leave `{payment-id}` in the path and send the braces to the server.\n */\nconst PATH_PLACEHOLDER = /\\{([a-zA-Z_$][a-zA-Z0-9_$.-]*)\\}/g;\n\n/**\n * Render a route path as the `Path(...)` call that builds the URL.\n *\n * Literal segments stay string literals and dynamic ones go through `Segment(...)`, so exactly the\n * values that came from the caller are percent-encoded. `params` says where a value lives: spread\n * across the signature, or behind one `pathParams` argument when the route declares a model.\n */\nexport function buildPathExpression(path: string, params?: ParamSource, bindings?: ReadonlyMap<string, string>): string {\n const args = path\n .split('/')\n .filter(Boolean)\n .map(raw => {\n PATH_PLACEHOLDER.lastIndex = 0;\n const match = PATH_PLACEHOLDER.exec(raw);\n if (!match || match[0] !== raw) return quoteCSharpString(raw);\n const value =\n params && params.kind !== 'params'\n ? `pathParams.${toCSharpPropertyName(match[1]!)}`\n : (bindings?.get(match[1]!) ?? toCSharpParameterName(match[1]!));\n return `http.Segment(${value})`;\n });\n return `http.Path(${args.join(', ')})`;\n}\n\n// ─── Parameters ────────────────────────────────────────────────────────────\n\n/**\n * Identifiers a generated method binds or reads besides its path parameters: the other arguments\n * {@link buildMethodParams} can declare, the trailing `CancellationToken`, the locals the body\n * declares, and the client's own `http` constructor parameter. A path parameter under one of these\n * names would duplicate an argument (CS0100), clash with a local (CS0136), or hide `http`.\n */\nconst METHOD_LOCALS = ['body', 'query', 'customHeaders', 'pathParams', 'cancellationToken', 'response', 'headers', 'http'] as const;\n\n/**\n * The C# parameter name each inline path parameter is spread into the signature under, keyed by its\n * declared name. Keyword-escaped (`@class`), and suffixed when it lands on one of\n * {@link METHOD_LOCALS} (`body_`). Empty when the route has no inline params.\n */\nfunction bindPathParams(route: OpRouteNode): Map<string, string> {\n if (route.params?.kind !== 'params') return new Map();\n return bindCSharpParameterNames(\n route.params.nodes.map(n => n.name),\n METHOD_LOCALS,\n );\n}\n\ninterface MethodParam {\n name: string;\n type: string;\n optional: boolean;\n}\n\n/**\n * The method signature, in the order a caller reads it: path, body, query, headers — but with every\n * required parameter ahead of every optional one.\n *\n * C# rejects a required parameter after an optional one, which Kotlin allows, so the contract's own\n * order cannot always survive. The relative order within each group is kept, and a trailing\n * `CancellationToken` is appended by the caller.\n */\nfunction buildMethodParams(route: OpRouteNode, op: OpOperationNode, ctx: RenderContext, pathBindings: ReadonlyMap<string, string>): MethodParam[] {\n const params: MethodParam[] = [];\n\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const node of route.params.nodes) {\n params.push({ name: pathBindings.get(node.name)!, type: renderCSharpType(node.type, ctx, true), optional: false });\n }\n } else {\n // Not `params`, which is a C# keyword: the argument would have to be written `@params`.\n params.push({ name: 'pathParams', type: renderParamSourceType(route.params, ctx, ''), optional: false });\n }\n }\n\n const body = op.request?.bodies[0];\n if (body) {\n switch (classifyContentType(body.contentType)) {\n case 'multipart':\n // The caller assembles the parts; the declared contract type describes the fields\n // rather than a value the client can send as one object.\n params.push({ name: 'body', type: 'IEnumerable<SdkPart>', optional: false });\n break;\n case 'binary':\n params.push({ name: 'body', type: 'byte[]', optional: false });\n break;\n case 'text':\n params.push({ name: 'body', type: 'string', optional: false });\n break;\n default:\n params.push({ name: 'body', type: renderCSharpType(body.bodyType, ctx, true), optional: false });\n }\n }\n\n const base = methodBase(deriveMethodName(op, route));\n if (op.query) {\n params.push({ name: 'query', type: renderParamSourceType(op.query, ctx, `${base}Query`), optional: allFieldsOptional(op.query) });\n }\n if (op.headers) {\n params.push({\n name: 'customHeaders',\n type: renderParamSourceType(op.headers, ctx, `${base}Headers`),\n optional: allFieldsOptional(op.headers),\n });\n }\n\n const widened = params.map(p => (p.optional && !p.type.endsWith('?') ? { ...p, type: `${p.type}?` } : p));\n return [...widened.filter(p => !p.optional), ...widened.filter(p => p.optional)];\n}\n\n/** Whether every field of a param source may be omitted, making the whole argument optional. */\nfunction allFieldsOptional(source: ParamSource): boolean {\n if (source.kind !== 'params') return true;\n return source.nodes.every(node => Boolean(node.optional) || node.default !== undefined);\n}\n\nfunction renderParamSourceType(source: ParamSource, ctx: RenderContext, generatedName: string): string {\n if (source.kind === 'ref') return renderCSharpType({ kind: 'ref', name: source.name }, ctx, true);\n if (source.kind === 'type') return renderCSharpType(source.node, ctx, true);\n // The record emitted for this method, or a plain map when the block declares nothing.\n return source.nodes.length > 0 ? generatedName : 'IReadOnlyDictionary<string, string>';\n}\n\n// ─── Method naming ─────────────────────────────────────────────────────────\n\n/**\n * The SDK method name, in the same priority order every ContractKit SDK uses: an explicit `sdk:`,\n * then the operation's `name:`, then a name inferred from the verb and path. C# spells it\n * PascalCase with an `Async` suffix, which is what a .NET caller expects of a `Task`-returning\n * method.\n */\nexport function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {\n if (op.sdk) return `${toCSharpTypeName(op.sdk)}Async`;\n if (op.name) return `${toCSharpTypeName(op.name)}Async`;\n return `${inferMethodName(op.method, route.path)}Async`;\n}\n\nfunction inferMethodName(method: string, path: string): string {\n const parts = [toCSharpTypeName(method)];\n for (const segment of path.split('/').filter(Boolean)) {\n if (segment.startsWith('{')) parts.push(`By${toCSharpTypeName(segment.slice(1, -1))}`);\n else parts.push(toCSharpTypeName(segment));\n }\n return parts.join('');\n}\n","import { xmlDocLines } from './naming.js';\n\nexport interface SdkAggregatorClient {\n className: string;\n propertyName: string;\n}\n\n/**\n * Generate the SDK entry point: one property per generated client, all sharing a single\n * [SdkHttp] and therefore a single `HttpClient`.\n *\n * The Python SDK gives each sub-client its own connection pool; that is a bug worth not repeating,\n * since a caller holding one SDK expects one set of connections.\n */\nexport function generateSdkCs(namespaceName: string, sdkName: string, clients: readonly SdkAggregatorClient[]): string {\n const lines: string[] = ['// <auto-generated/>', '// Generated by @contractkit/plugin-csharp. Do not edit manually.', '#nullable enable', ''];\n lines.push('using System;');\n if (clients.length > 0) lines.push(`using ${namespaceName}.Clients;`);\n lines.push(`using ${namespaceName}.Runtime;`);\n lines.push('');\n lines.push(`namespace ${namespaceName};`);\n lines.push('');\n lines.push(\n ...xmlDocLines(\n 'Entry point to the generated SDK.\\n\\n' +\n 'Holds one SdkHttp, shared by every client, so the SDK keeps a single connection pool.\\n' +\n 'Disposing it disposes the underlying HttpClient, unless you supplied your own.',\n '',\n ),\n );\n lines.push(`public sealed class ${sdkName} : IDisposable`);\n lines.push('{');\n lines.push(` public ${sdkName}(SdkOptions options)`);\n lines.push(' {');\n lines.push(' Http = new SdkHttp(options);');\n for (const client of clients) lines.push(` ${client.propertyName} = new ${client.className}(Http);`);\n lines.push(' }');\n lines.push('');\n lines.push(' public SdkHttp Http { get; }');\n for (const client of clients) {\n lines.push('');\n lines.push(` public ${client.className} ${client.propertyName} { get; }`);\n }\n lines.push('');\n lines.push(' public void Dispose()');\n lines.push(' {');\n lines.push(' Http.Dispose();');\n lines.push(' }');\n lines.push('}');\n lines.push('');\n return lines.join('\\n');\n}\n","import type { ContractRootNode, ContractTypeNode, FieldNode, ModelNode } from '@contractkit/core';\nimport { collectTypeRefs, resolveEffectiveFields } from '@contractkit/core';\nimport { sanitizeCSharpTypeName, toCSharpTypeName } from './naming.js';\n\n/**\n * C# needs a name for every shape a caller can hold. The `.ck` language does not: a union, an enum,\n * or an object literal can appear anonymously inside a field. This pass walks every model in the\n * project and assigns each such node a stable C# declaration, so the type renderer can emit a name\n * and the file emitter can emit the declaration behind it.\n *\n * It runs once over all contract roots rather than per file, because a discriminated union declared\n * in one file makes its member records, which may live in any other file, implement its interface.\n */\n\nexport type HoistKind = 'enum' | 'record' | 'plainUnion' | 'discriminatedUnion' | 'tuple';\n\nexport interface HoistedMember {\n /** The C# type of the member: a model name, or a hoisted declaration's name. */\n typeName: string;\n /** Nested record name inside a plain union's abstract record (`OfPayment`). */\n wrapperName?: string;\n /** Discriminator value for a discriminated union member. */\n tag?: string;\n type: ContractTypeNode;\n}\n\nexport interface HoistedDecl {\n kind: HoistKind;\n name: string;\n /** The `.ck` file whose models file carries this declaration. */\n ownerFile: string;\n /** Whether a distinct `<Name>Input` twin has to be emitted alongside it. */\n needsInput: boolean;\n /** Rendered references become `Name?` — the union had a `null` member. */\n nullable?: boolean;\n members?: HoistedMember[];\n discriminator?: string;\n fields?: FieldNode[];\n values?: string[];\n items?: ContractTypeNode[];\n description?: string;\n}\n\nexport interface HoistResult {\n /** The declaration standing in for an anonymous node, keyed by AST node identity. */\n byNode: Map<ContractTypeNode, HoistedDecl>;\n byName: Map<string, HoistedDecl>;\n /** Declarations each `.ck` file's models file has to emit, in collection order. */\n byFile: Map<string, HoistedDecl[]>;\n /** Model record name → the union interfaces it must declare it implements. */\n memberships: Map<string, string[]>;\n}\n\nexport interface HoistOptions {\n modelIndex: ReadonlyMap<string, ModelNode>;\n modelsWithInput: ReadonlySet<string>;\n warn?: (message: string, file: string) => void;\n}\n\n/** Analyse every model in the project and name the anonymous types that need a C# declaration. */\nexport function collectHoistedTypes(roots: readonly ContractRootNode[], opts: HoistOptions): HoistResult {\n const state: State = {\n ...opts,\n byNode: new Map(),\n byName: new Map(),\n byFile: new Map(),\n memberships: new Map(),\n taken: new Set(roots.flatMap(r => r.models.map(m => m.name))),\n };\n\n for (const root of roots) {\n for (const model of root.models) {\n if (model.type) {\n // A model alias occupies a name already, so only a union claims it here: everything\n // else an alias can hold is emitted directly as that model's own declaration.\n walkType(model.type, model.name, root.file, state, true, model.description);\n }\n for (const field of model.fields) {\n walkType(field.type, `${model.name}${toCSharpTypeName(field.name)}`, root.file, state, false, field.description);\n }\n }\n }\n\n return { byNode: state.byNode, byName: state.byName, byFile: state.byFile, memberships: state.memberships };\n}\n\ninterface State extends HoistOptions {\n byNode: Map<ContractTypeNode, HoistedDecl>;\n byName: Map<string, HoistedDecl>;\n byFile: Map<string, HoistedDecl[]>;\n memberships: Map<string, string[]>;\n /** Every name already claimed by a model or an earlier hoist, so a new one cannot collide. */\n taken: Set<string>;\n}\n\n/**\n * Walk one type, hoisting the nodes that need a name and recursing into the rest.\n *\n * @param atAliasRoot - True when the node is a model's own `type`, i.e. it already has a name.\n * Only unions are claimed there; other shapes are emitted by the model generator itself.\n */\nfunction walkType(type: ContractTypeNode, path: string, ownerFile: string, state: State, atAliasRoot: boolean, description?: string): void {\n switch (type.kind) {\n case 'union':\n hoistPlainUnion(type, path, ownerFile, state, atAliasRoot, description);\n return;\n case 'discriminatedUnion':\n hoistDiscriminatedUnion(type, path, ownerFile, state, atAliasRoot, description);\n return;\n case 'enum':\n if (!atAliasRoot) {\n hoist(\n type,\n { kind: 'enum', name: claimFor(path, state, false), ownerFile, needsInput: false, values: type.values, description },\n state,\n );\n }\n return;\n case 'inlineObject':\n if (!atAliasRoot) hoistRecord(type, type.fields, path, ownerFile, state, description);\n else type.fields.forEach(f => walkType(f.type, `${path}${toCSharpTypeName(f.name)}`, ownerFile, state, false, f.description));\n return;\n case 'intersection': {\n if (atAliasRoot) {\n type.members.forEach(m => walkType(m, path, ownerFile, state, true));\n return;\n }\n const { fields } = resolveEffectiveFields(type, state.modelIndex);\n hoistRecord(type, fields, path, ownerFile, state, description);\n return;\n }\n case 'tuple':\n type.items.forEach((item, i) => walkType(item, `${path}Item${i}`, ownerFile, state, false));\n // Every arity is hoisted. `ValueTuple` does not serialize as a JSON array, and a\n // property-level `[JsonConverter]` cannot reach a tuple nested inside a `List<>`. A\n // hoisted record carries a type-level converter, which travels everywhere the type does.\n hoist(\n type,\n {\n kind: 'tuple',\n name: claimFor(path, state, false),\n ownerFile,\n needsInput: type.items.some(t => typeNeedsInput(t, state)),\n items: type.items,\n description,\n },\n state,\n );\n return;\n case 'array':\n walkType(type.item, path, ownerFile, state, false);\n return;\n case 'record':\n walkType(type.value, path, ownerFile, state, false);\n return;\n case 'lazy':\n walkType(type.inner, path, ownerFile, state, atAliasRoot, description);\n return;\n default:\n return;\n }\n}\n\nfunction hoistRecord(node: ContractTypeNode, fields: FieldNode[], path: string, ownerFile: string, state: State, description?: string): void {\n const name = claimFor(path, state, false);\n for (const f of fields) walkType(f.type, `${name}${toCSharpTypeName(f.name)}`, ownerFile, state, false, f.description);\n hoist(\n node,\n {\n kind: 'record',\n name,\n ownerFile,\n needsInput: fields.some(f => f.visibility !== 'normal' || typeNeedsInput(f.type, state)),\n fields,\n description,\n },\n state,\n );\n}\n\n/**\n * A plain union becomes an abstract record with one nested member record per member, so a caller can\n * switch over it. Two shapes are recognised first because C# expresses them natively: a union whose\n * only non-null member is `T` is just `T?`, and a union of string literals is an enum.\n */\nfunction hoistPlainUnion(\n type: ContractTypeNode & { kind: 'union' },\n path: string,\n ownerFile: string,\n state: State,\n atAliasRoot: boolean,\n description?: string,\n): void {\n const nullable = type.members.some(m => m.kind === 'scalar' && m.name === 'null');\n const members = type.members.filter(m => !(m.kind === 'scalar' && m.name === 'null'));\n\n // `union(T, null)` is C#'s own nullable type; an abstract record would only get in the way.\n if (members.length <= 1) {\n if (members[0]) walkType(members[0], path, ownerFile, state, false);\n return;\n }\n\n if (members.every(m => m.kind === 'literal' && typeof m.value === 'string')) {\n const values = members.map(m => String((m as ContractTypeNode & { kind: 'literal' }).value));\n hoist(type, { kind: 'enum', name: claimFor(path, state, atAliasRoot), ownerFile, needsInput: false, nullable, values, description }, state);\n return;\n }\n\n const name = claimFor(path, state, atAliasRoot);\n const used = new Set<string>();\n const hoisted: HoistedMember[] = [];\n for (const member of members) {\n walkType(member, `${name}${toCSharpTypeName(memberLabel(member, state))}`, ownerFile, state, false);\n const typeName = memberTypeName(member, state);\n hoisted.push({ typeName, wrapperName: uniqueIn(`Of${toCSharpTypeName(memberLabel(member, state))}`, used), type: member });\n }\n\n hoist(\n type,\n {\n kind: 'plainUnion',\n name,\n ownerFile,\n needsInput: members.some(m => typeNeedsInput(m, state)),\n nullable,\n members: hoisted,\n description,\n },\n state,\n );\n}\n\n/**\n * A discriminated union becomes an interface its member records implement directly, with a converter\n * that dispatches on the tag. An interface rather than an abstract base: a record has single\n * inheritance, and one contract can belong to several unions. Members must be model refs or inline\n * objects, and the discriminator field must be a `literal` — an `enum` discriminator is legal in the\n * source language but leaves no statically known tag, so the union degrades to a raw JSON value.\n */\nfunction hoistDiscriminatedUnion(\n type: ContractTypeNode & { kind: 'discriminatedUnion' },\n path: string,\n ownerFile: string,\n state: State,\n atAliasRoot: boolean,\n description?: string,\n): void {\n const name = claimFor(path, state, atAliasRoot);\n const members: HoistedMember[] = [];\n\n for (const member of type.members) {\n const { fields } = resolveEffectiveFields(member, state.modelIndex);\n const discriminatorField = fields.find(f => f.name === type.discriminator);\n const tagType = discriminatorField?.type.kind === 'lazy' ? discriminatorField.type.inner : discriminatorField?.type;\n if (!tagType || tagType.kind !== 'literal') {\n state.warn?.(\n `Discriminated union '${name}' has a member whose '${type.discriminator}' is not a literal, so its tag is not known at build time; ` +\n `emitting a raw JSON value instead of an interface.`,\n ownerFile,\n );\n release(name, state, atAliasRoot);\n return;\n }\n\n const tag = String(tagType.value);\n if (member.kind === 'ref') {\n members.push({ typeName: member.name, tag, type: member });\n } else {\n // An inline member has no record of its own yet; name it after the tag it carries.\n const memberPath = `${name}${toCSharpTypeName(tag)}`;\n hoistRecord(member, fields, memberPath, ownerFile, state, undefined);\n const decl = state.byNode.get(member);\n if (!decl) {\n release(name, state, atAliasRoot);\n return;\n }\n members.push({ typeName: decl.name, tag, type: member });\n }\n }\n\n if (members.length === 0) {\n release(name, state, atAliasRoot);\n return;\n }\n\n const decl: HoistedDecl = {\n kind: 'discriminatedUnion',\n name,\n ownerFile,\n needsInput: type.members.some(m => typeNeedsInput(m, state)),\n members,\n discriminator: type.discriminator,\n description,\n };\n hoist(type, decl, state);\n\n // The member records declare the interface, wherever in the project they are generated.\n for (const member of members) {\n const list = state.memberships.get(member.typeName) ?? [];\n if (!list.includes(name)) list.push(name);\n state.memberships.set(member.typeName, list);\n }\n}\n\n/** A short label for a union member, used to name its member record and any nested hoist. */\nfunction memberLabel(type: ContractTypeNode, state: State): string {\n switch (type.kind) {\n case 'ref':\n return type.name;\n case 'scalar':\n return type.name;\n case 'array':\n return `${memberLabel(type.item, state)}List`;\n case 'record':\n return `${memberLabel(type.value, state)}Map`;\n case 'literal':\n return typeof type.value === 'string' ? type.value : String(type.value);\n case 'lazy':\n return memberLabel(type.inner, state);\n default: {\n const decl = state.byNode.get(type);\n return decl ? decl.name : 'Member';\n }\n }\n}\n\n/** The C# type a union member is wrapped around, once any nested hoisting has happened. */\nfunction memberTypeName(type: ContractTypeNode, state: State): string {\n const decl = state.byNode.get(type);\n if (decl) return decl.name;\n if (type.kind === 'ref') return type.name;\n return '';\n}\n\n/**\n * Whether rendering `type` for a request body differs from rendering it for a response, i.e. it\n * reaches a model that has a distinct `Input` variant. Drives whether a hoisted declaration needs\n * an `Input` twin of its own.\n */\nfunction typeNeedsInput(type: ContractTypeNode, state: State): boolean {\n const refs = new Set<string>();\n collectTypeRefs(type, refs);\n if ([...refs].some(r => state.modelsWithInput.has(r))) return true;\n return hasVisibilityField(type);\n}\n\nfunction hasVisibilityField(type: ContractTypeNode): boolean {\n switch (type.kind) {\n case 'inlineObject':\n return type.fields.some(f => f.visibility !== 'normal' || hasVisibilityField(f.type));\n case 'array':\n return hasVisibilityField(type.item);\n case 'record':\n return hasVisibilityField(type.value);\n case 'lazy':\n return hasVisibilityField(type.inner);\n case 'tuple':\n return type.items.some(hasVisibilityField);\n case 'union':\n case 'intersection':\n case 'discriminatedUnion':\n return type.members.some(hasVisibilityField);\n default:\n return false;\n }\n}\n\nfunction hoist(node: ContractTypeNode, decl: HoistedDecl, state: State): void {\n state.byNode.set(node, decl);\n state.byName.set(decl.name, decl);\n const list = state.byFile.get(decl.ownerFile) ?? [];\n list.push(decl);\n state.byFile.set(decl.ownerFile, list);\n}\n\n/**\n * Reserve a C# declaration name, suffixing until it is free. The path arrives already composed\n * from PascalCase parts, so it is only sanitized — re-casing it would fold `MV` back to `Mv`.\n *\n * A union that *is* a model's declared type keeps that model's name: it already owns it, and the\n * model generator emits nothing else under it.\n */\nfunction claimFor(path: string, state: State, atAliasRoot: boolean): string {\n if (atAliasRoot) return path;\n return uniqueIn(sanitizeCSharpTypeName(path), state.taken);\n}\n\n/** Give a reserved name back, for a hoist that turned out not to be expressible. */\nfunction release(name: string, state: State, atAliasRoot: boolean): void {\n if (!atAliasRoot) state.taken.delete(name);\n}\n\nfunction uniqueIn(base: string, taken: Set<string>): string {\n if (!taken.has(base)) {\n taken.add(base);\n return base;\n }\n let n = 2;\n while (taken.has(`${base}${n}`)) n++;\n taken.add(`${base}${n}`);\n return `${base}${n}`;\n}\n","/**\n * The `Runtime/SdkRuntime.cs` file: the `HttpClient` wrapper every generated client is built on.\n *\n * Nothing here comes from outside the BCL, so a generated SDK restores and builds with no NuGet\n * feed at all. The TypeScript, Python and Kotlin SDKs likewise read and write their own bodies\n * rather than delegating to a content-negotiation layer.\n */\n\n/** Generate `Runtime/SdkRuntime.cs` for `namespaceName`. Content depends on nothing but the namespace. */\nexport function generateRuntimeCs(namespaceName: string): string {\n return `// <auto-generated/>\n// Generated by @contractkit/plugin-csharp. Do not edit manually.\n#nullable enable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ${namespaceName}.Runtime;\n\n/// <summary>\n/// How to reach the service.\n/// </summary>\npublic sealed class SdkOptions\n{\n /// <summary>Origin, optionally with a path prefix. Operation paths are appended to it.</summary>\n public required string BaseUrl { get; init; }\n\n /// <summary>\n /// Called once per request. Authentication belongs here: returning a fresh map each time lets a\n /// token be refreshed without rebuilding the SDK.\n /// </summary>\n public Func<CancellationToken, ValueTask<IReadOnlyDictionary<string, string>>>? Headers { get; init; }\n\n /// <summary>\n /// Supply your own client to control handlers, proxies or retries. When you do, the SDK never\n /// disposes it. Leave it null and the SDK creates and owns one.\n /// </summary>\n public HttpClient? HttpClient { get; init; }\n\n /// <summary>\n /// How bodies, query values and headers are serialized. Defaults to <see cref=\"SdkJson.Options\"/>,\n /// which carries the converters the contract's scalar types need.\n /// </summary>\n public JsonSerializerOptions Json { get; init; } = SdkJson.Options;\n}\n\n/// <summary>\n/// A status the contract does not account for.\n/// </summary>\n/// <remarks>\n/// Derives from <see cref=\"HttpRequestException\"/>, so it can be caught alongside any other client\n/// failure, and passes the status through to <c>StatusCode</c> for callers that catch the base type.\n/// </remarks>\npublic class SdkException : HttpRequestException\n{\n public SdkException(int status, string body, HttpResponseHeaders? responseHeaders = null, string? message = null)\n#if NETSTANDARD2_0\n // .NET Standard 2.0's HttpRequestException carries no status of its own. Status below does,\n // so nothing is lost but the base type's own StatusCode property.\n : base(message ?? $\"Request failed with status {status}\")\n#else\n : base(message ?? $\"Request failed with status {status}\", null, ToStatusCode(status))\n#endif\n {\n Status = status;\n Body = body;\n ResponseHeaders = responseHeaders;\n }\n\n /// <summary>The HTTP status the service returned.</summary>\n public int Status { get; }\n\n /// <summary>The raw response body, read as UTF-8 text.</summary>\n public string Body { get; }\n\n /// <summary>The response headers, when the failure came from a response rather than a missing header.</summary>\n public HttpResponseHeaders? ResponseHeaders { get; }\n\n private bool _jsonParsed;\n private JsonElement? _json;\n\n /// <summary>\n /// The body parsed as JSON, or null when it is not JSON. Error contracts usually are.\n /// </summary>\n public JsonElement? Json\n {\n get\n {\n if (_jsonParsed) return _json;\n _jsonParsed = true;\n try\n {\n using var document = JsonDocument.Parse(Body);\n // Clone detaches the element from the document being disposed here.\n _json = document.RootElement.Clone();\n }\n catch (JsonException)\n {\n _json = null;\n }\n return _json;\n }\n }\n\n /// <summary>\n /// Read the error body as <typeparamref name=\"T\"/>, or null when it does not parse. Operations\n /// whose thrown statuses declare a body generate an alias naming the type to use here.\n /// </summary>\n public T? TryReadBody<T>(JsonSerializerOptions? options = null)\n where T : class\n {\n try\n {\n return JsonSerializer.Deserialize<T>(Body, options ?? SdkJson.Options);\n }\n catch (JsonException)\n {\n return null;\n }\n }\n\n#if !NETSTANDARD2_0\n private static HttpStatusCode? ToStatusCode(int status) =>\n status is >= 100 and <= 599 ? (HttpStatusCode)status : null;\n#endif\n}\n\n/// <summary>\n/// One response, with its body already read.\n/// </summary>\n/// <remarks>\n/// Reading the body eagerly is what allows a generated method to check the status, then the content\n/// type, then decode, which is exactly what an operation declaring several statuses or several\n/// mimes has to do.\n/// </remarks>\npublic sealed class SdkResponse\n{\n private string? _text;\n\n public SdkResponse(HttpResponseMessage message, byte[] bytes)\n {\n Message = message;\n Bytes = bytes;\n }\n\n public HttpResponseMessage Message { get; }\n\n /// <summary>The body as raw bytes.</summary>\n public byte[] Bytes { get; }\n\n public int Status => (int)Message.StatusCode;\n\n /// <summary>The response mime without its parameters, so <c>application/json; charset=utf-8</c> matches.</summary>\n public string ContentType => Message.Content.Headers.ContentType?.MediaType ?? string.Empty;\n\n /// <summary>The body decoded as UTF-8.</summary>\n public string Text => _text ??= Encoding.UTF8.GetString(Bytes);\n\n /// <summary>\n /// The first value of a response or content header, or null when the service did not send it.\n /// </summary>\n public string? Header(string name)\n {\n if (Message.Headers.TryGetValues(name, out var values)) return values.FirstOrDefault();\n if (Message.Content.Headers.TryGetValues(name, out var contentValues)) return contentValues.FirstOrDefault();\n return null;\n }\n}\n\n/// <summary>\n/// One part of a multipart request body.\n/// </summary>\npublic sealed record SdkPart(string Name, HttpContent Content, string? FileName = null)\n{\n /// <summary>A plain text field.</summary>\n public static SdkPart Text(string name, string value) => new(name, new StringContent(value, Encoding.UTF8));\n\n /// <summary>A file field, sent with a filename and its own content type.</summary>\n public static SdkPart File(string name, byte[] bytes, string fileName, string contentType = \"application/octet-stream\")\n {\n var content = new ByteArrayContent(bytes);\n content.Headers.ContentType = new MediaTypeHeaderValue(contentType);\n return new SdkPart(name, content, fileName);\n }\n}\n\n/// <summary>\n/// Issues requests and turns anything the contract does not describe into an <see cref=\"SdkException\"/>.\n/// </summary>\n/// <remarks>\n/// Every value bound for a path, query, header or form field is turned into text by serializing it\n/// the same way it would be serialized into a JSON body. That is what keeps a <c>Guid</c>, a\n/// <c>DateTimeOffset</c>, a <c>TimeSpan</c> or an enum spelled identically wherever it appears in a\n/// request, without a line of per-type code in the generator.\n/// </remarks>\npublic sealed class SdkHttp : IDisposable\n{\n private readonly SdkOptions _options;\n private readonly bool _ownsClient;\n\n public SdkHttp(SdkOptions options)\n {\n _options = options;\n _ownsClient = options.HttpClient is null;\n Client = options.HttpClient ?? new HttpClient();\n Json = options.Json;\n }\n\n public HttpClient Client { get; }\n\n public JsonSerializerOptions Json { get; }\n\n /// <summary>\n /// The PATCH verb.\n /// </summary>\n /// <remarks>\n /// <c>HttpMethod</c> carries a static for every other verb a contract can declare, but not for\n /// this one on every framework the SDK builds against, so it is spelled once here rather than\n /// allocated per call.\n /// </remarks>\n public static readonly HttpMethod Patch = new HttpMethod(\"PATCH\");\n\n /// <summary>\n /// Send one request and read its body.\n /// </summary>\n /// <remarks>\n /// <c>expectStatuses</c> carries the statuses the operation declares as outcomes rather than\n /// failures, such as a 404 the contract gives a meaning. Everything outside 2xx and that set\n /// throws.\n /// </remarks>\n /// <exception cref=\"SdkException\">On a status the contract does not declare.</exception>\n public async Task<SdkResponse> ExecuteAsync(\n HttpMethod method,\n string path,\n IEnumerable<KeyValuePair<string, string>>? query = null,\n IEnumerable<KeyValuePair<string, string>>? headers = null,\n HttpContent? content = null,\n IReadOnlyCollection<int>? expectStatuses = null,\n CancellationToken cancellationToken = default)\n {\n using var request = new HttpRequestMessage(method, BuildUrl(path, query));\n if (content is not null) request.Content = content;\n\n if (_options.Headers is not null)\n {\n foreach (var entry in await _options.Headers(cancellationToken).ConfigureAwait(false))\n {\n request.Headers.TryAddWithoutValidation(entry.Key, entry.Value);\n }\n }\n\n if (headers is not null)\n {\n foreach (var entry in headers)\n {\n request.Headers.TryAddWithoutValidation(entry.Key, entry.Value);\n }\n }\n\n var message = await Client.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);\n#if NETSTANDARD2_0\n // The cancellable overload arrived in .NET 5. ResponseContentRead above has already buffered\n // the body, so this read is a copy rather than a wait on the network.\n var bytes = await message.Content.ReadAsByteArrayAsync().ConfigureAwait(false);\n#else\n var bytes = await message.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);\n#endif\n var response = new SdkResponse(message, bytes);\n\n var status = response.Status;\n if ((status < 200 || status > 299) && (expectStatuses is null || !expectStatuses.Contains(status)))\n {\n throw new SdkException(status, response.Text, message.Headers);\n }\n\n return response;\n }\n\n /// <summary>Decode a JSON response body.</summary>\n /// <exception cref=\"SdkException\">When the body is JSON null.</exception>\n public T ReadJson<T>(SdkResponse response)\n {\n var value = JsonSerializer.Deserialize<T>(response.Bytes, Json);\n if (value is null)\n {\n throw new SdkException(response.Status, response.Text, response.Message.Headers, \"Response body was null\");\n }\n\n return value;\n }\n\n /// <summary>\n /// Read a response header the contract declares as required.\n /// </summary>\n /// <exception cref=\"SdkException\">When the service did not send it, since the caller was promised a value.</exception>\n public string RequireHeader(SdkResponse response, string name) =>\n response.Header(name)\n ?? throw new SdkException(response.Status, response.Text, response.Message.Headers, $\"Response is missing the required header '{name}'\");\n\n /// <summary>Join path segments onto the base URL. Each segment is already escaped.</summary>\n public string Path(params string[] segments) => segments.Length == 0 ? string.Empty : \"/\" + string.Join(\"/\", segments);\n\n /// <summary>The escaped text form of a single value, for use as a path segment.</summary>\n public string Segment<T>(T value) => Uri.EscapeDataString(ScalarText(JsonSerializer.SerializeToElement(value, Json)) ?? string.Empty);\n\n /// <summary>\n /// Every property of <paramref name=\"value\"/> as a key and value pair. A list property repeats\n /// its key; a null property is omitted.\n /// </summary>\n public IEnumerable<KeyValuePair<string, string>> Params<T>(T value)\n {\n if (value is null) yield break;\n\n var element = JsonSerializer.SerializeToElement(value, Json);\n if (element.ValueKind != JsonValueKind.Object) yield break;\n\n foreach (var property in element.EnumerateObject())\n {\n if (property.Value.ValueKind == JsonValueKind.Array)\n {\n foreach (var item in property.Value.EnumerateArray())\n {\n if (ScalarText(item) is { } itemText) yield return new KeyValuePair<string, string>(property.Name, itemText);\n }\n }\n else if (ScalarText(property.Value) is { } text)\n {\n yield return new KeyValuePair<string, string>(property.Name, text);\n }\n }\n }\n\n /// <summary>A JSON body. Sent as a buffered string so the request carries a Content-Length.</summary>\n public HttpContent JsonContent<T>(T value, string mediaType) =>\n new StringContent(JsonSerializer.Serialize(value, Json), Encoding.UTF8, mediaType);\n\n /// <summary>A form-encoded body, built from the same property walk as the query string.</summary>\n public HttpContent FormContent<T>(T value) => new FormUrlEncodedContent(Params(value));\n\n /// <summary>A multipart body.</summary>\n public HttpContent MultipartContent(IEnumerable<SdkPart> parts)\n {\n var content = new MultipartFormDataContent();\n foreach (var part in parts)\n {\n if (part.FileName is null) content.Add(part.Content, part.Name);\n else content.Add(part.Content, part.Name, part.FileName);\n }\n\n return content;\n }\n\n /// <summary>A text body with an explicit mime.</summary>\n public HttpContent TextContent(string value, string mediaType) => new StringContent(value, Encoding.UTF8, mediaType);\n\n /// <summary>A binary body with an explicit mime.</summary>\n public HttpContent BinaryContent(byte[] value, string mediaType)\n {\n var content = new ByteArrayContent(value);\n content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);\n return content;\n }\n\n /// <summary>The text a scalar JSON value travels as outside a body, or null when it is absent.</summary>\n public static string? ScalarText(JsonElement element) =>\n element.ValueKind switch\n {\n JsonValueKind.Null or JsonValueKind.Undefined => null,\n JsonValueKind.String => element.GetString(),\n JsonValueKind.True => \"true\",\n JsonValueKind.False => \"false\",\n _ => element.GetRawText(),\n };\n\n public void Dispose()\n {\n if (_ownsClient) Client.Dispose();\n }\n\n private string BuildUrl(string path, IEnumerable<KeyValuePair<string, string>>? query)\n {\n var builder = new StringBuilder(_options.BaseUrl.TrimEnd('/')).Append(path);\n if (query is null) return builder.ToString();\n\n var first = true;\n foreach (var entry in query)\n {\n builder.Append(first ? '?' : '&');\n first = false;\n builder.Append(Uri.EscapeDataString(entry.Key)).Append('=').Append(Uri.EscapeDataString(entry.Value));\n }\n\n return builder.ToString();\n }\n}\n`;\n}\n","/**\n * The `Runtime/Converters.cs` file: the shared `JsonSerializerOptions` and the converters for the\n * three ContractKit scalars whose BCL type does not serialize the way the contract says it travels.\n *\n * These live in the generated output rather than in a published NuGet package so the SDK has no\n * dependency at all. The same choice the Python plugin makes with `_base_client.py` and the Kotlin\n * plugin with `Serializers.kt`.\n *\n * Enums, unions and tuples are not handled here: each carries a `[JsonConverter]` attribute of its\n * own, so it serializes correctly under any options. These three are options-level, which is why\n * anything serializing a generated model by hand has to pass `SdkJson.Options`.\n */\n\nimport type { CSharpDateTypes } from './codegen-models.js';\n\n/**\n * A `date` carried as a `DateTime`, under `dateTypes: \"datetime\"`.\n *\n * Registered on every framework, not only the old one: the framework's own `DateTime` handling writes\n * a full round-trip timestamp, which is not what the contract says a `date` looks like. Safe to make\n * options-level because `datetime` maps to `DateTimeOffset`, so nothing else in a generated model is\n * a `DateTime`.\n */\nconst ISO_DATE_CONVERTER = `/// <summary>\n/// A calendar date, as <c>yyyy-MM-dd</c>, carried in the date part of a <c>DateTime</c>.\n/// </summary>\n/// <remarks>\n/// The time is midnight and the kind is unspecified: a contract's <c>date</c> names neither, and\n/// pretending to either would put a zone offset on the wire.\n/// </remarks>\npublic sealed class IsoDateConverter : JsonConverter<DateTime>\n{\n public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected a date string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected a date string.\");\n if (DateTime.TryParseExact(text, \"yyyy-MM-dd\", CultureInfo.InvariantCulture, DateTimeStyles.None, out var exact))\n {\n return exact;\n }\n\n // A service sending more than the contract promised is read for the part it promised.\n if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed))\n {\n return parsed.Date;\n }\n\n throw new JsonException($\"'{text}' is not a date.\");\n }\n\n public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString(\"yyyy-MM-dd\", CultureInfo.InvariantCulture));\n }\n}\n\n`;\n\n/** A `date` carried as the polyfilled `DateOnly`, under the default `dateTypes: \"dateonly\"`. */\nconst DATE_ONLY_CONVERTER = `\n/// <summary>\n/// A calendar date, as <c>yyyy-MM-dd</c>.\n/// </summary>\n/// <remarks>\n/// Compiled only where <c>DateOnly</c> is the SDK's own polyfill. The wire form is the one the\n/// framework's converter writes on net10.0, so a service reads a body from either leg of the build.\n/// </remarks>\npublic sealed class DateOnlyConverter : JsonConverter<DateOnly>\n{\n public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected a date string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected a date string.\");\n if (!DateOnly.TryParse(text, CultureInfo.InvariantCulture, out var value))\n {\n throw new JsonException($\"'{text}' is not a date.\");\n }\n\n return value;\n }\n\n public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString());\n }\n}\n`;\n\n/**\n * Generate `Runtime/Converters.cs`.\n *\n * Which date converter is registered follows `dateTypes`, since that decides the CLR type a `date`\n * arrives as and serialization dispatches on nothing else.\n */\nexport function generateConvertersCs(namespaceName: string, dateTypes: CSharpDateTypes = 'dateonly'): string {\n const asDateTime = dateTypes === 'datetime';\n\n return `// <auto-generated/>\n// Generated by @contractkit/plugin-csharp. Do not edit manually.\n#nullable enable\n\nusing System;\nusing System.Buffers;\nusing System.Globalization;\nusing System.Numerics;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Xml;\n\nnamespace ${namespaceName}.Runtime;\n\n/// <summary>\n/// How the SDK reads and writes JSON.\n/// </summary>\n/// <remarks>\n/// Unknown properties are skipped, which is the default, so a service adding a field does not break\n/// an older client. Serialize a generated model with these options: three of the contract's scalar\n/// types need the converters registered here.\n/// </remarks>\npublic static class SdkJson\n{\n public static readonly JsonSerializerOptions Options = CreateOptions();\n\n private static JsonSerializerOptions CreateOptions()\n {\n var options = new JsonSerializerOptions();\n options.Converters.Add(new BigIntegerConverter());\n options.Converters.Add(new DecimalStringConverter());\n options.Converters.Add(new IsoTimeSpanConverter());\n${asDateTime ? ' options.Converters.Add(new IsoDateConverter());\\n' : ''}#if NETSTANDARD2_0\n // These are the SDK's own types on this framework, so System.Text.Json has no built-in\n // converter for them. On net10.0 the framework handles them and these are not compiled.\n${asDateTime ? '' : ' options.Converters.Add(new DateOnlyConverter());\\n'} options.Converters.Add(new TimeOnlyConverter());\n#endif\n return options;\n }\n}\n\n/// <summary>\n/// An arbitrary-precision integer. Written as a plain digit string.\n/// </summary>\n/// <remarks>\n/// Reading accepts a digit string, the <c>123n</c> form the TypeScript SDK writes, and a JSON\n/// number, so a body written by any ContractKit client reads back here.\n/// </remarks>\npublic sealed class BigIntegerConverter : JsonConverter<BigInteger>\n{\n public override BigInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.String)\n {\n var text = reader.GetString() ?? throw new JsonException(\"Expected a digit string for a bigint.\");\n return BigInteger.Parse(text.TrimEnd('n'), NumberStyles.Integer, CultureInfo.InvariantCulture);\n }\n\n if (reader.TokenType == JsonTokenType.Number)\n {\n // Read the raw token rather than a long: the value may be wider than any BCL integer,\n // which is the whole reason the contract called it a bigint. Copied to an array rather\n // than handed to the span overload of GetString, which netstandard2.0 does not have.\n var raw = Encoding.UTF8.GetString(reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray());\n return BigInteger.Parse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture);\n }\n\n throw new JsonException($\"Expected a JSON string or number for a bigint, got {reader.TokenType}.\");\n }\n\n public override void Write(Utf8JsonWriter writer, BigInteger value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));\n }\n}\n\n/// <summary>\n/// An exact decimal number. Travels as a quoted JSON string, never as a JSON number.\n/// </summary>\n/// <remarks>\n/// A JSON number has already been through a double by the time it reaches this converter, so the\n/// precision the contract asked for is gone. Reading an unquoted number is rejected for that\n/// reason, which matches the Kotlin SDK and the server's own schema.\n/// </remarks>\npublic sealed class DecimalStringConverter : JsonConverter<decimal>\n{\n public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected a quoted decimal string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected a decimal string.\");\n return decimal.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);\n }\n\n public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));\n }\n}\n\n/// <summary>\n/// A duration, as an ISO 8601 string such as <c>PT1H30M</c>.\n/// </summary>\n/// <remarks>\n/// System.Text.Json writes a <c>TimeSpan</c> as <c>d.hh:mm:ss</c> by default, which no other\n/// ContractKit SDK would read, so this converter is not optional.\n/// </remarks>\npublic sealed class IsoTimeSpanConverter : JsonConverter<TimeSpan>\n{\n public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected an ISO 8601 duration string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected an ISO 8601 duration string.\");\n try\n {\n return XmlConvert.ToTimeSpan(text);\n }\n catch (FormatException error)\n {\n throw new JsonException($\"'{text}' is not an ISO 8601 duration.\", error);\n }\n }\n\n public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(XmlConvert.ToString(value));\n }\n}\n\n${asDateTime ? ISO_DATE_CONVERTER : ''}#if NETSTANDARD2_0\n${asDateTime ? '' : DATE_ONLY_CONVERTER}\n/// <summary>\n/// A time of day, as <c>HH:mm:ss</c>, with a seven-digit fraction when there is one.\n/// </summary>\n/// <remarks>\n/// Compiled only where <c>TimeOnly</c> is the SDK's own polyfill, and writing what the framework's\n/// own converter writes on net10.0, so a service reads a body from either leg of the build.\n/// </remarks>\npublic sealed class TimeOnlyConverter : JsonConverter<TimeOnly>\n{\n public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.String)\n {\n throw new JsonException($\"Expected a time-of-day string, got {reader.TokenType}.\");\n }\n\n var text = reader.GetString() ?? throw new JsonException(\"Expected a time-of-day string.\");\n if (!TimeOnly.TryParse(text, CultureInfo.InvariantCulture, out var value))\n {\n throw new JsonException($\"'{text}' is not a time of day.\");\n }\n\n return value;\n }\n\n public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value.ToString());\n }\n}\n\n#endif\n`;\n}\n","/**\n * The `Runtime/Polyfills.cs` file: what .NET Standard 2.0 does not carry.\n *\n * Emitted only when the SDK targets netstandard2.0, and compiled only on that leg of a multi-target\n * build, so a project on net10.0 alone never sees any of it. Two groups, for two different reasons:\n *\n * - The attributes the C# compiler looks for before it will accept an `init` accessor, a `required`\n * member, or the records built on them. The compiler asks for these by full name and does not care\n * which assembly declares them, so `internal` copies are enough and cannot collide with a\n * consumer's own.\n * - `DateOnly` and `TimeOnly`, which arrived in .NET 6. These are declared in the SDK's own runtime\n * namespace rather than in `System`, because a consumer is free to reference a package that\n * backfills `System.DateOnly` for their own code and two declarations of one full name are\n * ambiguous wherever they meet. Generated files import the runtime namespace, so `DateOnly`\n * resolves to the polyfill here on netstandard2.0 and to the framework's type on net10.0 without a\n * line of conditional code in a model.\n */\n\n/** Generate `Runtime/Polyfills.cs` for `namespaceName`. Content depends on nothing but the namespace. */\nexport function generatePolyfillsCs(namespaceName: string): string {\n return `// <auto-generated/>\n// Generated by @contractkit/plugin-csharp. Do not edit manually.\n#nullable enable\n\n#if NETSTANDARD2_0\n\nusing System;\nusing System.Globalization;\n\nnamespace System.Runtime.CompilerServices\n{\n /// <summary>\n /// The marker the compiler requires before it will emit an <c>init</c> accessor.\n /// </summary>\n internal static class IsExternalInit\n {\n }\n\n /// <summary>\n /// Marks a member whose initialization the compiler requires at every construction site.\n /// </summary>\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\n internal sealed class RequiredMemberAttribute : Attribute\n {\n }\n\n /// <summary>\n /// Names a compiler feature a member depends on, so a compiler that does not have it refuses the\n /// member rather than misreading it.\n /// </summary>\n [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]\n internal sealed class CompilerFeatureRequiredAttribute : Attribute\n {\n public CompilerFeatureRequiredAttribute(string featureName)\n {\n FeatureName = featureName;\n }\n\n public string FeatureName { get; }\n\n public bool IsOptional { get; init; }\n\n public const string RefStructs = nameof(RefStructs);\n\n public const string RequiredMembers = nameof(RequiredMembers);\n }\n}\n\nnamespace System.Diagnostics.CodeAnalysis\n{\n /// <summary>\n /// Marks a constructor that sets every required member itself.\n /// </summary>\n [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]\n internal sealed class SetsRequiredMembersAttribute : Attribute\n {\n }\n}\n\nnamespace ${namespaceName}.Runtime\n{\n /// <summary>\n /// A calendar date with no time and no offset. Stands in for <c>System.DateOnly</c>.\n /// </summary>\n /// <remarks>\n /// Carries what a generated SDK and the code around it need: construction, ordering, conversion\n /// to and from <see cref=\"DateTime\"/>, and the <c>yyyy-MM-dd</c> form a contract's <c>date</c>\n /// travels as. Not a complete reimplementation of the framework type.\n /// </remarks>\n public readonly struct DateOnly : IEquatable<DateOnly>, IComparable<DateOnly>, IComparable\n {\n private readonly DateTime _value;\n\n public DateOnly(int year, int month, int day)\n {\n _value = new DateTime(year, month, day);\n }\n\n private DateOnly(DateTime value)\n {\n _value = value.Date;\n }\n\n public static DateOnly MinValue => new DateOnly(DateTime.MinValue);\n\n public static DateOnly MaxValue => new DateOnly(DateTime.MaxValue);\n\n public int Year => _value.Year;\n\n public int Month => _value.Month;\n\n public int Day => _value.Day;\n\n public int DayOfYear => _value.DayOfYear;\n\n public DayOfWeek DayOfWeek => _value.DayOfWeek;\n\n /// <summary>The date part of <paramref name=\"value\"/>, dropping its time and kind.</summary>\n public static DateOnly FromDateTime(DateTime value) => new DateOnly(value);\n\n /// <summary>This date at midnight, with an unspecified kind. What a XAML date picker binds to.</summary>\n public DateTime ToDateTime() => _value;\n\n /// <summary>This date at <paramref name=\"time\"/>, with an unspecified kind.</summary>\n public DateTime ToDateTime(TimeOnly time) => _value.Add(time.ToTimeSpan());\n\n public DateOnly AddDays(int value) => new DateOnly(_value.AddDays(value));\n\n public DateOnly AddMonths(int value) => new DateOnly(_value.AddMonths(value));\n\n public DateOnly AddYears(int value) => new DateOnly(_value.AddYears(value));\n\n public static DateOnly Parse(string s) => Parse(s, CultureInfo.InvariantCulture);\n\n /// <exception cref=\"FormatException\">When <paramref name=\"s\"/> is not a date.</exception>\n public static DateOnly Parse(string s, IFormatProvider? provider)\n {\n if (!TryParse(s, provider, out var result))\n {\n throw new FormatException(\"'\" + s + \"' is not a date.\");\n }\n\n return result;\n }\n\n public static bool TryParse(string? s, out DateOnly result) => TryParse(s, CultureInfo.InvariantCulture, out result);\n\n /// <remarks>\n /// The wire form is tried first and exactly; anything else the culture reads as a date is\n /// then taken by its date part, which is what the framework type does too.\n /// </remarks>\n public static bool TryParse(string? s, IFormatProvider? provider, out DateOnly result)\n {\n var culture = provider ?? CultureInfo.InvariantCulture;\n if (DateTime.TryParseExact(s, \"yyyy-MM-dd\", culture, DateTimeStyles.None, out var exact))\n {\n result = new DateOnly(exact);\n return true;\n }\n\n if (DateTime.TryParse(s, culture, DateTimeStyles.None, out var parsed))\n {\n result = new DateOnly(parsed);\n return true;\n }\n\n result = default;\n return false;\n }\n\n /// <summary>The ISO 8601 form, <c>yyyy-MM-dd</c>. Also how the date travels on the wire.</summary>\n public override string ToString() => _value.ToString(\"yyyy-MM-dd\", CultureInfo.InvariantCulture);\n\n public string ToString(string? format) => _value.ToString(format, CultureInfo.InvariantCulture);\n\n public string ToString(string? format, IFormatProvider? provider) => _value.ToString(format, provider);\n\n public bool Equals(DateOnly other) => _value == other._value;\n\n public override bool Equals(object? obj) => obj is DateOnly other && Equals(other);\n\n public override int GetHashCode() => _value.GetHashCode();\n\n public int CompareTo(DateOnly other) => _value.CompareTo(other._value);\n\n public int CompareTo(object? obj)\n {\n if (obj is null) return 1;\n if (obj is DateOnly other) return CompareTo(other);\n throw new ArgumentException(\"Object must be of type DateOnly.\", nameof(obj));\n }\n\n public static bool operator ==(DateOnly left, DateOnly right) => left.Equals(right);\n\n public static bool operator !=(DateOnly left, DateOnly right) => !left.Equals(right);\n\n public static bool operator <(DateOnly left, DateOnly right) => left.CompareTo(right) < 0;\n\n public static bool operator <=(DateOnly left, DateOnly right) => left.CompareTo(right) <= 0;\n\n public static bool operator >(DateOnly left, DateOnly right) => left.CompareTo(right) > 0;\n\n public static bool operator >=(DateOnly left, DateOnly right) => left.CompareTo(right) >= 0;\n }\n\n /// <summary>\n /// A time of day with no date and no offset. Stands in for <c>System.TimeOnly</c>.\n /// </summary>\n /// <remarks>\n /// At least zero and less than 24 hours, which is what separates it from the\n /// <see cref=\"TimeSpan\"/> a contract's <c>duration</c> maps to.\n /// </remarks>\n public readonly struct TimeOnly : IEquatable<TimeOnly>, IComparable<TimeOnly>, IComparable\n {\n private static readonly TimeSpan OneDay = TimeSpan.FromDays(1);\n\n /// <summary>Accepted on the way in: the wire form, with or without a fraction, and <c>HH:mm</c>.</summary>\n private static readonly string[] Formats = { \"HH:mm:ss.FFFFFFF\", \"HH:mm\" };\n\n private readonly TimeSpan _value;\n\n public TimeOnly(int hour, int minute)\n : this(new TimeSpan(hour, minute, 0))\n {\n }\n\n public TimeOnly(int hour, int minute, int second)\n : this(new TimeSpan(hour, minute, second))\n {\n }\n\n public TimeOnly(int hour, int minute, int second, int millisecond)\n : this(new TimeSpan(0, hour, minute, second, millisecond))\n {\n }\n\n private TimeOnly(TimeSpan value)\n {\n if (value < TimeSpan.Zero || value >= OneDay)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"A time of day is at least zero and less than 24 hours.\");\n }\n\n _value = value;\n }\n\n public static TimeOnly MinValue => new TimeOnly(TimeSpan.Zero);\n\n public static TimeOnly MaxValue => new TimeOnly(OneDay - TimeSpan.FromTicks(1));\n\n public int Hour => _value.Hours;\n\n public int Minute => _value.Minutes;\n\n public int Second => _value.Seconds;\n\n public int Millisecond => _value.Milliseconds;\n\n public long Ticks => _value.Ticks;\n\n /// <summary>The time part of <paramref name=\"value\"/>.</summary>\n public static TimeOnly FromDateTime(DateTime value) => new TimeOnly(value.TimeOfDay);\n\n /// <exception cref=\"ArgumentOutOfRangeException\">When <paramref name=\"value\"/> is negative or a day or more.</exception>\n public static TimeOnly FromTimeSpan(TimeSpan value) => new TimeOnly(value);\n\n /// <summary>This time as a span since midnight. What a XAML time picker binds to.</summary>\n public TimeSpan ToTimeSpan() => _value;\n\n public static TimeOnly Parse(string s) => Parse(s, CultureInfo.InvariantCulture);\n\n /// <exception cref=\"FormatException\">When <paramref name=\"s\"/> is not a time of day.</exception>\n public static TimeOnly Parse(string s, IFormatProvider? provider)\n {\n if (!TryParse(s, provider, out var result))\n {\n throw new FormatException(\"'\" + s + \"' is not a time of day.\");\n }\n\n return result;\n }\n\n public static bool TryParse(string? s, out TimeOnly result) => TryParse(s, CultureInfo.InvariantCulture, out result);\n\n public static bool TryParse(string? s, IFormatProvider? provider, out TimeOnly result)\n {\n var culture = provider ?? CultureInfo.InvariantCulture;\n if (DateTime.TryParseExact(s, Formats, culture, DateTimeStyles.None, out var exact))\n {\n result = new TimeOnly(exact.TimeOfDay);\n return true;\n }\n\n if (DateTime.TryParse(s, culture, DateTimeStyles.None, out var parsed))\n {\n result = new TimeOnly(parsed.TimeOfDay);\n return true;\n }\n\n result = default;\n return false;\n }\n\n /// <summary>\n /// The ISO 8601 form: <c>HH:mm:ss</c>, and a fraction of seven digits when there is one.\n /// </summary>\n /// <remarks>\n /// Byte for byte what System.Text.Json's own converter writes for a <c>TimeOnly</c> on\n /// net10.0 — including the seven digits, which it does not trim — so a service cannot tell\n /// which leg of the build sent a body.\n /// </remarks>\n public override string ToString() =>\n _value.Ticks % TimeSpan.TicksPerSecond == 0\n ? _value.ToString(\"hh':'mm':'ss\", CultureInfo.InvariantCulture)\n : _value.ToString(\"hh':'mm':'ss'.'fffffff\", CultureInfo.InvariantCulture);\n\n public string ToString(string? format) => _value.ToString(format, CultureInfo.InvariantCulture);\n\n public string ToString(string? format, IFormatProvider? provider) => _value.ToString(format, provider);\n\n public bool Equals(TimeOnly other) => _value == other._value;\n\n public override bool Equals(object? obj) => obj is TimeOnly other && Equals(other);\n\n public override int GetHashCode() => _value.GetHashCode();\n\n public int CompareTo(TimeOnly other) => _value.CompareTo(other._value);\n\n public int CompareTo(object? obj)\n {\n if (obj is null) return 1;\n if (obj is TimeOnly other) return CompareTo(other);\n throw new ArgumentException(\"Object must be of type TimeOnly.\", nameof(obj));\n }\n\n public static bool operator ==(TimeOnly left, TimeOnly right) => left.Equals(right);\n\n public static bool operator !=(TimeOnly left, TimeOnly right) => !left.Equals(right);\n\n public static bool operator <(TimeOnly left, TimeOnly right) => left.CompareTo(right) < 0;\n\n public static bool operator <=(TimeOnly left, TimeOnly right) => left.CompareTo(right) <= 0;\n\n public static bool operator >(TimeOnly left, TimeOnly right) => left.CompareTo(right) > 0;\n\n public static bool operator >=(TimeOnly left, TimeOnly right) => left.CompareTo(right) >= 0;\n }\n}\n\n#endif\n`;\n}\n","/**\n * The project file a generated SDK needs to build on its own.\n *\n * Emitted with `ifAbsent`, so it is created once and then belongs to the user: a project will add a\n * package id, a version, an analyzer set and a signing key of its own, and regenerating over that\n * would throw the work away. Generated C# sources are rewritten every run; this is not. A project\n * created before a scaffold change therefore keeps its own file — the README carries the snippet to\n * paste when the change is one the project wants.\n */\n\n/** The frameworks a generated SDK can be built for. */\nexport type CSharpTargetFramework = 'netstandard2.0' | 'net10.0';\n\n/**\n * What the scaffold pins. One object so a bump is one edit.\n *\n * A single-framework SDK on `net10.0` has no dependency list to go with it: it uses only\n * `System.Text.Json` and `HttpClient` from the shared framework, so `dotnet build` restores with no\n * NuGet feed reachable at all. `netstandard2.0` is the exception — `System.Text.Json` is a package\n * there, and one that brings `System.Memory` and `System.Threading.Tasks.Extensions` with it.\n */\nexport const SCAFFOLD_VERSIONS = {\n targetFramework: 'net10.0',\n systemTextJson: '10.0.12',\n /** The oldest language version the generated sources compile under: records, `required`, primary constructors. */\n netstandardLangVersion: '12.0',\n} as const;\n\n/** The framework the scaffold targets when the config names none. */\nexport const DEFAULT_TARGET_FRAMEWORKS: readonly CSharpTargetFramework[] = [SCAFFOLD_VERSIONS.targetFramework];\n\n/**\n * Generate `<SdkName>.csproj`.\n *\n * `ImplicitUsings` is off because generated files carry an explicit `using` block of their own, and\n * leaving it on would make the output depend on the SDK's implicit set rather than on what the\n * generator wrote.\n *\n * Only a build that includes `netstandard2.0` pins `LangVersion` or references a package. On its own,\n * `net10.0` defaults to the newest language version the SDK knows, and pinning one here would hold a\n * project back rather than help it.\n */\nexport function generateCsproj(\n namespaceName: string,\n sdkName: string,\n targetFrameworks: readonly CSharpTargetFramework[] = DEFAULT_TARGET_FRAMEWORKS,\n): string {\n const frameworks =\n targetFrameworks.length === 1\n ? ` <TargetFramework>${targetFrameworks[0]}</TargetFramework>`\n : ` <TargetFrameworks>${targetFrameworks.join(';')}</TargetFrameworks>`;\n\n const netstandard = targetFrameworks.includes('netstandard2.0')\n ? `\n <!-- .NET Standard 2.0 predates the language features the generated sources use. -->\n <PropertyGroup Condition=\"'$(TargetFramework)' == 'netstandard2.0'\">\n <LangVersion>${SCAFFOLD_VERSIONS.netstandardLangVersion}</LangVersion>\n </PropertyGroup>\n\n <!-- The one framework where System.Text.Json is a package rather than part of the platform. -->\n <ItemGroup Condition=\"'$(TargetFramework)' == 'netstandard2.0'\">\n <PackageReference Include=\"System.Text.Json\" Version=\"${SCAFFOLD_VERSIONS.systemTextJson}\" />\n </ItemGroup>\n`\n : '';\n\n return `<!-- Created once by @contractkit/plugin-csharp. Yours to edit: it is never regenerated. -->\n<Project Sdk=\"Microsoft.NET.Sdk\">\n\n <PropertyGroup>\n${frameworks}\n <Nullable>enable</Nullable>\n <ImplicitUsings>disable</ImplicitUsings>\n <RootNamespace>${namespaceName}</RootNamespace>\n <AssemblyName>${sdkName}</AssemblyName>\n </PropertyGroup>\n${netstandard}\n</Project>\n`;\n}\n"],"mappings":";AAAA,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,YAAY,WAAW,cAAc,aAAa,QAAQ,WAAW,qBAAqB;AAanG;AAAA,EACI,mBAAAA;AAAA,EACA;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;;;ACtBP,SAAS,iBAAiB,wBAAwB,wBAAwB,sBAAsB;;;ACazF,IAAM,kBAAuC,oBAAI,IAAI;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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