@contractkit/plugin-typescript 0.23.0 → 0.23.1

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-contract.ts","../src/codegen-operation.ts","../src/ts-render.ts","../src/codegen-sdk.ts","../src/codegen-plain-types.ts","../src/path-utils.ts"],"sourcesContent":["import { resolve, join, relative, dirname, basename } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, rmdirSync } from 'node:fs';\nimport { generateContract } from './codegen-contract.js';\nimport { generateOp } from './codegen-operation.js';\nimport type {\n ContractKitPlugin,\n PluginContext,\n ContractRootNode,\n OpRootNode,\n ModelNode,\n IncrementalManifest,\n IncrementalUnit,\n IncrementalOutputFile,\n} from '@contractkit/core';\nimport {\n runIncrementalCodegen,\n parseIncrementalManifest,\n emptyIncrementalManifest,\n serializeIncrementalManifest,\n hashFingerprint,\n collectTransitiveModelRefs,\n collectTypeRefs,\n} from '@contractkit/core';\nimport {\n generateSdk,\n generateSdkOptions,\n generateSdkAggregator,\n generateAreaClient,\n deriveClientClassName,\n deriveClientPropertyName,\n deriveAreaClientClassName,\n deriveAreaPropertyName,\n deriveSubareaClientClassName,\n deriveSubareaPropertyName,\n getAreaSubarea,\n hasPublicOperations,\n type SdkClientInfo,\n type SdkAreaInfo,\n} from './codegen-sdk.js';\nimport { generatePlainTypes } from './codegen-plain-types.js';\nimport {\n TEMPLATE_VAR_RE,\n resolveTemplate,\n commonDir,\n computeOpOutPath,\n computeContractOutPath,\n computeSdkOutPath,\n computeSdkAreaClientOutPath,\n computeSdkTypeOutPath,\n generateBarrelFiles,\n computePubliclyReachableTypes,\n} from './path-utils.js';\n\n// ─── Sub-config interfaces ─────────────────────────────────────────────────\n\nexport interface ServerConfig {\n /** Directory (relative to rootDir) where server files are written. Default: rootDir. */\n baseDir?: string;\n /** When true, `output.types` emits Zod schema files (via `generateContract`). When false/omitted, emits plain TypeScript. */\n zod?: boolean;\n output?: {\n /** Path template for Koa router files. Supports {filename}, {dir}, {area}. */\n routes?: string;\n /** Path template for type/schema files. Supports {filename}, {dir}, {area}. */\n types?: string;\n };\n /** Import path template for service implementations. */\n servicePathTemplate?: string;\n /** Whether to emit handlers for `internal` operations. Default true. */\n includeInternal?: boolean;\n}\n\nexport interface SdkConfig {\n baseDir?: string;\n name?: string;\n zod?: boolean;\n output?: {\n sdk?: string;\n types?: string;\n clients?: string;\n };\n includeInternal?: boolean;\n}\n\nexport interface ZodConfig {\n baseDir?: string;\n output?: string;\n}\n\nexport interface TypesConfig {\n baseDir?: string;\n output?: string;\n}\n\nexport interface TypescriptPluginConfig {\n server?: ServerConfig;\n sdk?: SdkConfig;\n zod?: ZodConfig;\n types?: TypesConfig;\n}\n\n// ─── Caching constants ─────────────────────────────────────────────────────\n\n/** Bumped when the codegen output shape changes in a way that should bust every per-file fingerprint. */\nexport const TYPESCRIPT_CODEGEN_VERSION = '1';\n\n/** Filename for the persisted TypeScript manifest under the CLI cache directory. */\nconst CACHE_MANIFEST_FILENAME = 'typescript-manifest.json';\n\n// ─── Plugin entry points ──────────────────────────────────────────────────\n\nconst plugin: ContractKitPlugin = {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n const config = ctx.options as TypescriptPluginConfig;\n await runTypescriptCodegen(inputs, ctx, config, ctx.rootDir);\n },\n};\n\nexport default plugin;\n\n/** Build a `@contractkit/plugin-typescript` instance with explicit configuration, for programmatic use. */\nexport function createTypescriptPlugin(config: TypescriptPluginConfig, rootDir: string): ContractKitPlugin {\n return {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n await runTypescriptCodegen(inputs, ctx, config, rootDir);\n },\n };\n}\n\n/**\n * Shared orchestration. Each sub-generator (server / sdk / zod / types) contributes a\n * set of cacheable units (per-file fingerprints) plus a set of always-regenerated global\n * files (aggregators, barrels, sdk-options). Units share a single manifest so the cache\n * survives cross-cutting reads — the manifest lives at `<rootDir>/.contractkit-typescript-manifest.json`.\n *\n * Honors `ctx.cacheEnabled` — `--force` bypasses the manifest entirely.\n */\nasync function runTypescriptCodegen(\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n ctx: PluginContext,\n config: TypescriptPluginConfig,\n rootDir: string,\n): Promise<void> {\n const manifestPath = resolve(ctx.cacheDir, CACHE_MANIFEST_FILENAME);\n const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n\n const units: IncrementalUnit[] = [];\n const globalFiles: IncrementalOutputFile[] = [];\n\n if (config.server) collectServerOutput(config.server, rootDir, inputs, units);\n if (config.sdk) collectSdkOutput(config.sdk, rootDir, inputs, units, globalFiles);\n if (config.zod) collectZodOutput(config.zod, rootDir, inputs, units);\n if (config.types) collectTypesOutput(config.types, rootDir, inputs, units);\n\n const result = runIncrementalCodegen({\n codegenVersion: TYPESCRIPT_CODEGEN_VERSION,\n prevManifest,\n globalFiles,\n units,\n // Paths are absolute, so existsSync works directly.\n fileExists: existsSync,\n });\n\n deleteStalePaths(result.deletedPaths);\n\n for (const { relativePath, content } of result.filesToWrite) {\n ctx.emitFile(relativePath, content);\n }\n\n writeManifest(manifestPath, result.manifest);\n}\n\n// ─── Cross-file dependency analysis ────────────────────────────────────────\n\n/** Build a quick lookup from model name → its definition. */\nfunction buildModelMap(contractRoots: readonly ContractRootNode[]): Map<string, ModelNode> {\n const map = new Map<string, ModelNode>();\n for (const root of contractRoots) {\n for (const model of root.models) map.set(model.name, model);\n }\n return map;\n}\n\n/** Collect every model referenced by this contract root (own models' fields + bases). Used to slice cross-file fingerprint inputs to just what this file actually depends on. */\nfunction collectContractRootRefs(root: ContractRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const m of root.models) {\n if (m.type) seeds.push(m.type);\n for (const f of m.fields) seeds.push(f.type);\n if (m.bases) {\n for (const b of m.bases) seeds.push({ kind: 'ref', name: b } as Parameters<typeof collectTypeRefs>[0]);\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\n/** Collect every model referenced by an op root's routes/operations (transitive). */\nfunction collectOpRootRefs(root: OpRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const route of root.routes) {\n if (route.params) seeds.push(...paramSourceTypes(route.params));\n for (const op of route.operations) {\n if (op.query) seeds.push(...paramSourceTypes(op.query));\n if (op.headers) seeds.push(...paramSourceTypes(op.headers));\n if (op.request) {\n for (const body of op.request.bodies) seeds.push(body.bodyType);\n }\n for (const resp of op.responses) {\n if (resp.bodyType) seeds.push(resp.bodyType);\n if (resp.headers) {\n for (const h of resp.headers) seeds.push(h.type);\n }\n }\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\nfunction paramSourceTypes(src: NonNullable<OpRootNode['routes'][number]['params']>): Parameters<typeof collectTypeRefs>[0][] {\n const out: Parameters<typeof collectTypeRefs>[0][] = [];\n if (src.kind === 'params') {\n for (const n of src.nodes) out.push(n.type);\n } else if (src.kind === 'ref') {\n out.push({ kind: 'ref', name: src.name } as Parameters<typeof collectTypeRefs>[0]);\n } else if (src.kind === 'type') {\n out.push(src.node);\n }\n return out;\n}\n\n/** Build a sorted, JSON-stable record of (modelName -> outPath) for refs this unit depends on. */\nfunction sliceOutPathMap(refs: Set<string>, modelOutPaths: Map<string, string>, modelsWithInput: Set<string>, modelsWithOutput: Set<string>): Record<string, string> {\n const slice: Record<string, string> = {};\n for (const ref of [...refs].sort()) {\n const p = modelOutPaths.get(ref);\n if (p) slice[ref] = p;\n if (modelsWithInput.has(ref)) {\n const ip = modelOutPaths.get(`${ref}Input`);\n if (ip) slice[`${ref}Input`] = ip;\n }\n if (modelsWithOutput.has(ref)) {\n const op = modelOutPaths.get(`${ref}Output`);\n if (op) slice[`${ref}Output`] = op;\n }\n }\n return slice;\n}\n\n/** Slice modelsWithInput/Output to only the names relevant to this unit. */\nfunction sliceModelSet(refs: Set<string>, ownNames: Set<string>, set: Set<string>): string[] {\n const result: string[] = [];\n for (const name of set) {\n if (refs.has(name) || ownNames.has(name)) result.push(name);\n }\n return result.sort();\n}\n\n// ─── Server sub-generator ──────────────────────────────────────────────────\n\nfunction collectServerOutput(\n config: ServerConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const serverBase = resolve(rootDir, config.baseDir ?? '.');\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const subConfigKey = stableSubConfig(config);\n\n // Pre-pass: register all model → outPath. Cross-file refs need to resolve correctly,\n // which means we need the COMPLETE map (not a slice) — even though each unit's fingerprint\n // only includes its own slice.\n const serverModelOutPaths = new Map<string, string>();\n const typeEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeContractOutPath(ast.file, serverBase, config.output.types, '.ts', commonRoot, ast.meta);\n typeEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n serverModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) serverModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) serverModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── Per-contract-root types unit ──\n for (const { ast, typeOutPath } of typeEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'server-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `server-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n const renderCtx = {\n modelOutPaths: serverModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n };\n const content = config.zod ? generateContract(ast, renderCtx) : generatePlainTypes(ast, renderCtx);\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Per-op-root router unit ──\n for (const ast of inputs.opRoots) {\n const outPath = computeOpOutPath(ast.file, serverBase, config.output?.routes, '.router.ts', commonRoot, ast.meta);\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'server-router',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n // The router imports types from each contract root's type file; the slice covers exactly that.\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n servicePathTemplate: config.servicePathTemplate ?? null,\n includeInternal: config.includeInternal ?? true,\n sub: subConfigKey,\n });\n units.push({\n key: `server-router::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateOp(ast, {\n servicePathTemplate: config.servicePathTemplate,\n outPath,\n modelOutPaths: serverModelOutPaths,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n }),\n },\n ],\n });\n }\n}\n\n// ─── SDK sub-generator ─────────────────────────────────────────────────────\n\nfunction collectSdkOutput(\n config: SdkConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n globalFiles: IncrementalOutputFile[],\n): void {\n const sdkBase = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;\n const sdkName = config.name;\n const sdkOutput = config.output?.sdk;\n const sdkEntryPath = sdkOutput\n ? join(sdkBase, TEMPLATE_VAR_RE.test(sdkOutput) ? resolveTemplate(sdkOutput, { name: sdkName ?? 'sdk' }) : sdkOutput)\n : join(sdkBase, 'sdk.ts');\n const sdkOptionsPath = join(dirname(sdkEntryPath), 'sdk-options.ts');\n const subConfigKey = stableSubConfig(config);\n\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const ckCommonRoot = commonDir(allFiles, rootDir);\n\n const sdkModelOutPaths = new Map<string, string>();\n const sdkTypePaths: string[] = [];\n const sdkClientInfos: { outPath: string; className: string; propertyName: string }[] = [];\n\n // ── Pre-pass: SDK type files ──\n const sdkContractEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n const publicTypes = computePubliclyReachableTypes(inputs.opRoots, inputs.contractRoots, modelsWithInput, modelsWithOutput);\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeSdkTypeOutPath(ast.file, sdkBase, config.output.types, ckCommonRoot, ast.meta);\n if (!typeOutPath) continue;\n if (publicTypes !== null && !ast.models.some(m => publicTypes.has(m.name))) continue;\n sdkTypePaths.push(typeOutPath);\n sdkContractEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n sdkModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) sdkModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) sdkModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── SDK type units ──\n for (const { ast, typeOutPath } of sdkContractEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'sdk-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sdkOptionsPath,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n let content: string;\n if (config.zod) {\n content = generateContract(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n });\n } else {\n let rel = relative(dirname(typeOutPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n content = generatePlainTypes(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n jsonValueImportPath: rel,\n });\n }\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Bucket op roots by area/subarea ──\n interface AreaBucket {\n leaves: { ast: OpRootNode; outPath: string; subarea: string }[];\n inlineRoots: OpRootNode[];\n }\n const areaBuckets = new Map<string, AreaBucket>();\n const topLevelEntries: { ast: OpRootNode; outPath: string }[] = [];\n\n if (config.output?.clients) {\n for (const ast of inputs.opRoots) {\n const sdkOutPath = computeSdkOutPath(ast.file, sdkBase, config.output.clients, ckCommonRoot, ast.meta);\n if (!sdkOutPath || !hasPublicOperations(ast, config.includeInternal)) continue;\n const { area, subarea } = getAreaSubarea(ast);\n if (area && subarea) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.leaves.push({ ast, outPath: sdkOutPath, subarea });\n areaBuckets.set(area, bucket);\n } else if (area) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.inlineRoots.push(ast);\n areaBuckets.set(area, bucket);\n } else {\n topLevelEntries.push({ ast, outPath: sdkOutPath });\n }\n }\n\n // ── Per-leaf-client (area+subarea) units ──\n for (const [area, bucket] of areaBuckets.entries()) {\n for (const leaf of bucket.leaves) {\n const className = deriveSubareaClientClassName(area, leaf.subarea);\n sdkClientInfos.push({ outPath: leaf.outPath, className, propertyName: deriveSubareaPropertyName(leaf.subarea) });\n const refs = collectOpRootRefs(leaf.ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-leaf-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: leaf.outPath,\n root: leaf.ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n sdkOptionsPath,\n className,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-leaf-client::${leaf.outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: leaf.outPath,\n content: generateSdk(leaf.ast, {\n typeImportPathTemplate: undefined,\n outPath: leaf.outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n clientClassName: className,\n }),\n },\n ],\n });\n }\n }\n\n // ── Top-level (no area) client units ──\n for (const { ast, outPath } of topLevelEntries) {\n const className = deriveClientClassName(ast.file);\n sdkClientInfos.push({ outPath, className, propertyName: deriveClientPropertyName(ast.file) });\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-top-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-top-client::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateSdk(ast, {\n typeImportPathTemplate: undefined,\n outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n }),\n },\n ],\n });\n }\n }\n\n // ── Global files: sdk-options, aggregator, barrels, root index ──\n // sdk-options.ts is a constant; the aggregator is small (just imports + a wrapper class)\n // and depends on the cross-cutting client list, so it's cheap to regenerate every run.\n // Per-area `<area>.client.ts` files are cached as their own units below.\n globalFiles.push({ relativePath: sdkOptionsPath, content: generateSdkOptions() });\n\n const hasAnything = sdkClientInfos.length > 0 || areaBuckets.size > 0;\n const areaClientOutPaths = new Map<string, string>(); // area → absolute outPath of <area>.client.ts\n if (hasAnything) {\n const sdkEntryDir = dirname(sdkEntryPath);\n const sdkOptionsRel = relative(sdkEntryDir, sdkOptionsPath).replace(/\\.ts$/, '.js');\n const sdkOptionsImportPath = sdkOptionsRel.startsWith('.') ? sdkOptionsRel : './' + sdkOptionsRel;\n const sdkClassName = sdkName\n ? sdkName\n .split(/[-._\\s]+/)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('') + 'Sdk'\n : 'Sdk';\n\n const toClientImport = (sourceDir: string, info: { outPath: string; className: string; propertyName: string }): SdkClientInfo => {\n let rel = relative(sourceDir, info.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n return { className: info.className, propertyName: info.propertyName, importPath: rel };\n };\n\n const topLevelClients: SdkClientInfo[] = topLevelEntries.map(e =>\n toClientImport(sdkEntryDir, {\n outPath: e.outPath,\n className: deriveClientClassName(e.ast.file),\n propertyName: deriveClientPropertyName(e.ast.file),\n }),\n );\n\n // ── Per-area `<area>.client.ts` units ──\n const areaInfos: SdkAreaInfo[] = [];\n const sortedAreas = [...areaBuckets.entries()].sort(([a], [b]) => a.localeCompare(b));\n for (const [area, bucket] of sortedAreas) {\n const areaClientOutPath = computeSdkAreaClientOutPath(area, sdkBase, config.output!.clients);\n areaClientOutPaths.set(area, areaClientOutPath);\n const areaClassName = deriveAreaClientClassName(area);\n const areaPropertyName = deriveAreaPropertyName(area);\n sdkClientInfos.push({ outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName });\n\n const subareaClients = bucket.leaves\n .sort((a, b) => a.subarea.localeCompare(b.subarea))\n .map(l => ({\n propertyName: deriveSubareaPropertyName(l.subarea),\n client: toClientImport(dirname(areaClientOutPath), {\n outPath: l.outPath,\n className: deriveSubareaClientClassName(area, l.subarea),\n propertyName: deriveSubareaPropertyName(l.subarea),\n }),\n }));\n\n // Fingerprint covers every input the area client depends on:\n // - all inline roots (full AST)\n // - subarea client metadata (className / propertyName / import path)\n // - the modelOutPaths slice for refs across all inline roots\n // - modelsWithInput/Output slices\n const allInlineRefs = new Set<string>();\n for (const r of bucket.inlineRoots) {\n for (const ref of collectOpRootRefs(r, modelMap)) allInlineRefs.add(ref);\n }\n const fingerprint = hashFingerprint({\n kind: 'sdk-area-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: areaClientOutPath,\n area,\n inlineRoots: bucket.inlineRoots,\n subareaClients,\n outPathSlice: sliceOutPathMap(allInlineRefs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(allInlineRefs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(allInlineRefs, new Set(), modelsWithOutput),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n\n const inlineFilesForGen = bucket.inlineRoots.map(root => ({\n root,\n codegenOptions: {\n typeImportPathTemplate: undefined,\n outPath: areaClientOutPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n },\n }));\n\n units.push({\n key: `sdk-area-client::${areaClientOutPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: areaClientOutPath,\n content: generateAreaClient({\n area,\n outPath: areaClientOutPath,\n inlineFiles: inlineFilesForGen,\n subareaClients,\n sdkOptionsPath,\n }),\n },\n ],\n });\n\n areaInfos.push({\n area,\n client: toClientImport(sdkEntryDir, { outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName }),\n });\n }\n\n globalFiles.push({\n relativePath: sdkEntryPath,\n content: generateSdkAggregator({ topLevelClients, areas: areaInfos, sdkOptionsImportPath, sdkClassName }),\n });\n }\n\n const sdkSrcDir = dirname(sdkEntryPath);\n const sdkTypeBarrels = generateBarrelFiles(sdkTypePaths);\n for (const barrel of sdkTypeBarrels) globalFiles.push({ relativePath: barrel.outPath, content: barrel.content });\n\n const rootExports: string[] = [`export * from './${basename(sdkOptionsPath).replace(/\\.ts$/, '.js')}';`];\n if (hasAnything) rootExports.push(`export * from './${basename(sdkEntryPath).replace(/\\.ts$/, '.js')}';`);\n for (const c of sdkClientInfos) {\n let rel = relative(sdkSrcDir, c.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n for (const barrel of sdkTypeBarrels) {\n let rel = relative(sdkSrcDir, barrel.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n globalFiles.push({\n relativePath: join(sdkSrcDir, 'index.ts'),\n content: `// Auto-generated barrel file\\n${rootExports.sort().join('\\n')}\\n`,\n });\n}\n\n// ─── Zod sub-generator ─────────────────────────────────────────────────────\n\nfunction collectZodOutput(\n config: ZodConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const zodBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, zodBase, config.output, '.schema.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'zod',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `zod::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateContract(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput }),\n },\n ],\n });\n }\n}\n\n// ─── Plain types sub-generator ─────────────────────────────────────────────\n\nfunction collectTypesOutput(\n config: TypesConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const typesBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, typesBase, config.output, '.types.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'plain-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `plain-types::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generatePlainTypes(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput }),\n },\n ],\n });\n }\n}\n\n// ─── Manifest IO + cleanup ─────────────────────────────────────────────────\n\nfunction readManifest(manifestPath: string): IncrementalManifest {\n if (!existsSync(manifestPath)) return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n try {\n return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n }\n}\n\n/** Write the manifest to `manifestPath`. Creates parent dirs as needed. 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\nfunction deleteStalePaths(absPaths: string[]): void {\n if (absPaths.length === 0) return;\n const removedDirs = new Set<string>();\n for (const abs of absPaths) {\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(dirname(abs));\n }\n }\n // Walk up affected dirs and remove if empty. Bounded — stops at filesystem root or first non-empty dir.\n for (const dir of removedDirs) {\n let current = dir;\n while (current.length > 1) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = dirname(current);\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n\n/** Stringify a sub-config so it can participate in fingerprints. JSON.stringify gives stable output for typical config shapes. */\nfunction stableSubConfig(config: unknown): string {\n return JSON.stringify(config ?? null);\n}\n","import { relative, dirname } from 'node:path';\nimport type {\n ContractRootNode,\n ModelNode,\n FieldNode,\n ContractTypeNode,\n ScalarTypeNode,\n ArrayTypeNode,\n TupleTypeNode,\n RecordTypeNode,\n EnumTypeNode,\n LiteralTypeNode,\n UnionTypeNode,\n DiscriminatedUnionTypeNode,\n InlineObjectTypeNode,\n IntersectionTypeNode,\n ObjectMode,\n} from '@contractkit/core';\nimport {\n collectTypeRefs,\n computeModelsWithOutput as ckComputeModelsWithOutput,\n collectExternalOutputRefs as ckCollectExternalOutputRefs,\n} from '@contractkit/core';\n\n/**\n * Maps a ContractKit object mode to its Zod constructor name.\n *\n * @returns `\"z.strictObject\"` | `\"z.object\"` | `\"z.looseObject\"`\n */\nexport function modeToWrapper(mode: ObjectMode): string {\n switch (mode) {\n case 'strict':\n return 'z.strictObject';\n case 'strip':\n return 'z.object';\n case 'loose':\n return 'z.looseObject';\n }\n}\n\n// ─── Cross-file import resolution ─────────────────────────────────────────\n\n/** Cross-file context passed to `generateContract` to wire up imports and Input/Output variant tracking. */\nexport interface ContractCodegenContext {\n /** Map from model name → absolute output file path */\n modelOutPaths: Map<string, string>;\n /** Absolute output file path for the current contract file */\n currentOutPath: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /** If set, import JsonValue from this path instead of re-declaring it (avoids barrel re-export conflicts) */\n jsonValueImportPath?: string;\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Compute which models need Input variants, including transitive dependencies.\n * A model needs an Input variant if it has visibility-modified fields, OR if\n * any of its field types (recursively) reference a model that has an Input variant.\n */\nexport function computeModelsWithInput(models: ModelNode[], externalModelsWithInput: Set<string> = new Set()): Set<string> {\n const result = new Set<string>();\n\n // Initial pass: direct visibility modifiers\n for (const model of models) {\n if (model.fields.some(f => f.visibility !== 'normal')) {\n result.add(model.name);\n }\n }\n\n // Transitive closure: add models that reference models with Input variants,\n // including through base model inheritance.\n let changed = true;\n while (changed) {\n changed = false;\n for (const model of models) {\n if (result.has(model.name)) continue;\n const refs = new Set<string>();\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // A model that extends a parent with Input variants also needs an Input variant,\n // so that the write schema can extend ParentInput instead of Parent.\n if (model.bases) for (const b of model.bases) refs.add(b);\n // A type alias (model.type set) that references a model with Input variants\n // also needs an Input variant.\n if (model.type) collectTypeRefs(model.type, refs);\n for (const ref of refs) {\n if (result.has(ref) || externalModelsWithInput.has(ref)) {\n result.add(model.name);\n changed = true;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n lines.push(` * ${model.description}`);\n }\n\n const relPath = outPath ? relative(dirname(outPath), model.loc.file) : model.loc.file;\n lines.push(` * generated from [${model.name}](file://./${relPath}#L${model.loc.line})`);\n lines.push('*/');\n return lines;\n}\n\n/**\n * Generate a TypeScript module containing Zod schemas for every model in `root`.\n *\n * Emits up to three schemas per model when visibility modifiers are present:\n * `ModelBase` (all fields), `Model` (read — no writeonly), `ModelInput` (write — no readonly).\n *\n * @param root - The parsed contract root node.\n * @param context - Optional cross-file context for import resolution and Input/Output variant tracking.\n * @returns The full TypeScript source as a string.\n */\nexport function generateContract(root: ContractRootNode, context?: ContractCodegenContext): string {\n const needsDateTime = rootNeedsDateTime(root);\n const needsDuration = rootNeedsScalar(root, 'duration');\n const needsInterval = rootNeedsScalar(root, 'interval');\n const needsBinary = rootNeedsScalar(root, 'binary');\n const needsDatetime = rootNeedsScalar(root, 'datetime');\n const needsJson = rootNeedsScalar(root, 'json');\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = ckComputeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input refs needed for Input schema fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? ckCollectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n lines.push(`import { z } from 'zod';`);\n const luxonImports: string[] = [];\n if (needsDateTime) luxonImports.push('DateTime');\n if (needsDuration) luxonImports.push('Duration');\n if (needsInterval) luxonImports.push('Interval');\n if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n lines.push(`import { ${ref} } from '${importPath}';`);\n }\n lines.push('');\n if (needsBinary) {\n lines.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (needsDatetime) {\n lines.push(\n `const _ZodDatetime = z.preprocess((val) => typeof val === 'string' ? DateTime.fromISO(val) : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be in ISO 8601 format' }));`,\n );\n }\n if (needsInterval) {\n lines.push(\n `const _ZodInterval = z.preprocess((val) => typeof val === 'string' ? Interval.fromISO(val) : val, z.custom<Interval>((val) => val instanceof Interval && val.isValid, { message: 'Must be an ISO 8601 interval' })).transform(val => val.toISO()!);`,\n );\n }\n if (needsJson) {\n lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n lines.push(\n `const _ZodJson: z.ZodType<_JsonValue> = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(_ZodJson), z.record(z.string(), _ZodJson)]));`,\n );\n }\n if (needsBinary || needsDatetime || needsInterval || needsJson) lines.push('');\n\n const modelsWithWriteonly = new Set(root.models.filter(m => m.fields.some(f => f.visibility === 'writeonly')).map(m => m.name));\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n for (const model of topoSortModels(root.models)) {\n lines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, modelsWithWriteonly, modelMap, allModelsWithOutput));\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\n/**\n * If any ancestor in the base chain has a format(input=)/format(output=) transform,\n * the parent schema compiles to a `ZodPipe` (object().transform()) which has no `.extend()`.\n * To keep extension working, inline the parent's fields into the child and inherit format/mode\n * so the child re-applies the transform on the merged shape. Returns the model unchanged when\n * no ancestor has format, preserving the existing `.extend()`-based output.\n */\nfunction flattenFormatChain(model: ModelNode, modelMap: Map<string, ModelNode>): ModelNode {\n if (!model.bases || model.bases.length === 0) return model;\n // TODO(multi-base): currently only the first base is followed for format inheritance.\n // Multi-base format flattening will need a topological merge across all bases.\n const firstBase = model.bases[0]!;\n const parent = modelMap.get(firstBase);\n if (!parent) return model;\n const flatParent = flattenFormatChain(parent, modelMap);\n const parentHasFormat =\n (flatParent.inputCase !== undefined && flatParent.inputCase !== 'camel') ||\n (flatParent.outputCase !== undefined && flatParent.outputCase !== 'camel');\n if (!parentHasFormat) return model;\n\n const merged = new Map<string, FieldNode>();\n for (const f of flatParent.fields) merged.set(f.name, f);\n for (const f of model.fields) merged.set(f.name, f);\n\n return {\n ...model,\n bases: undefined,\n fields: [...merged.values()],\n inputCase: model.inputCase ?? flatParent.inputCase,\n outputCase: model.outputCase ?? flatParent.outputCase,\n mode: model.mode ?? flatParent.mode,\n };\n}\n\nfunction generateModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithWriteonly?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n modelsWithOutput?: Set<string>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);\n }\n\n const effective = modelMap ? flattenFormatChain(model, modelMap) : model;\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = effective.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(effective.name) ?? false);\n\n const lines = needsInputSplit\n ? generateThreeSchemaModel(effective, outPath, modelsWithInput, modelsWithWriteonly, modelMap)\n : generateSimpleModel(effective, outPath);\n\n // Emit Output type alias when this model (transitively) has format(output=...)\n if (modelsWithOutput?.has(effective.name)) {\n lines.push(`export type ${effective.name}Output = z.output<typeof ${effective.name}>;`);\n }\n\n return lines;\n}\n\nfunction generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export const ${model.name} = ${renderType(model.type!)};`);\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export const ${model.name}Input = ${renderInputType(model.type!, modelsWithInput)};`);\n lines.push(`export type ${model.name}Input = z.infer<typeof ${model.name}Input>;`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = z.output<typeof ${model.name}>;`);\n }\n return lines;\n}\n\nfunction generateSimpleModel(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const { inputCase, outputCase } = model;\n const hasInputTransform = !!inputCase && inputCase !== 'camel';\n const hasOutputTransform = !!outputCase && outputCase !== 'camel';\n\n if (hasInputTransform || hasOutputTransform) {\n const inputBody =\n inputCase === 'snake'\n ? renderFieldsAsSnakeCase(model.fields, model.mode)\n : inputCase === 'pascal'\n ? renderFieldsAsPascalCase(model.fields, model.mode)\n : renderFields(model.fields, model.mode);\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...inputBody.map(l => ` ${l}`));\n lines.push(`}).transform(data => ({`);\n for (const field of model.fields) {\n const inputKey = applyCase(field.name, inputCase);\n const outputKey = applyCase(field.name, outputCase);\n lines.push(` ${quoteKey(outputKey)}: data.${inputKey},`);\n }\n lines.push(`}));`);\n // When only outputCase is set, the developer-facing type is the schema's\n // pre-transform shape (camelCase). With inputCase, the post-transform\n // shape is what consumers work with.\n const typeSource = hasOutputTransform && !hasInputTransform ? 'input' : 'output';\n lines.push(`export type ${model.name} = z.${typeSource}<typeof ${model.name}>;`);\n return lines;\n }\n\n const body = renderFields(model.fields, model.mode);\n const bases = model.bases ?? [];\n if (bases.length > 0) {\n const head = bases[0]!;\n const tail = bases\n .slice(1)\n .map(b => `.extend(${b}.shape)`)\n .join('');\n lines.push(`export const ${model.name} = ${head}${tail}.extend({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n } else {\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n }\n\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n return lines;\n}\n\n/** Builds a Zod extension chain \"Head.extend(B.shape).extend(C.shape)...\" for a list of base names,\n * applying a per-base name resolver (e.g. choosing \"BaseInput\" for bases that have an Input variant). */\nfunction buildExtendChain(bases: string[], resolveName: (b: string) => string): { head: string; tail: string } {\n const head = resolveName(bases[0]!);\n const tail = bases\n .slice(1)\n .map(b => `.extend(${resolveName(b)}.shape)`)\n .join('');\n return { head, tail };\n}\n\nfunction collectEffectiveWritableFieldNames(modelName: string, modelMap: Map<string, ModelNode>): Set<string> {\n const model = modelMap.get(modelName);\n if (!model || model.type) return new Set();\n const result = new Set<string>();\n for (const base of model.bases ?? []) {\n for (const f of collectEffectiveWritableFieldNames(base, modelMap)) result.add(f);\n }\n for (const field of model.fields) {\n if (field.visibility === 'readonly') result.delete(field.name);\n else result.add(field.name);\n }\n return result;\n}\n\nfunction generateThreeSchemaModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithWriteonly?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n const lines: string[] = [];\n const name = model.name;\n\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const allFields = model.fields;\n const hasWriteonly = allFields.some(f => f.visibility === 'writeonly');\n\n const bases = model.bases ?? [];\n\n // Base schema — all fields (used internally when a submodel extends this one).\n // Only needed when this model has writeonly fields; otherwise Base === Read.\n if (hasWriteonly) {\n const baseBody = renderFields(allFields, model.mode);\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => (modelsWithWriteonly?.has(b) ? `${b}Base` : b));\n lines.push(`const ${name}Base = ${head}${tail}.extend({`);\n } else {\n lines.push(`const ${name}Base = ${wrapper}({`);\n }\n lines.push(...baseBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push('');\n }\n\n // Read schema — omit writeonly fields; extends parent read schema\n const readFields = allFields.filter(f => f.visibility !== 'writeonly');\n const readBody = renderFields(readFields, model.mode);\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => b);\n lines.push(`export const ${name} = ${head}${tail}.extend({`);\n } else {\n lines.push(`export const ${name} = ${wrapper}({`);\n }\n lines.push(...readBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name} = z.infer<typeof ${name}>;`);\n lines.push('');\n\n // Write schema — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read schema\n const writeFields = allFields.filter(f => f.visibility !== 'readonly');\n const writeBody = modelsWithInput ? renderInputFields(writeFields, modelsWithInput, model.mode) : renderFields(writeFields, model.mode);\n // Fields that become readonly in this model but were writable in a base must be omitted from\n // the base Input schema — Zod's .extend() cannot remove inherited fields.\n const fieldsToOmit = new Set<string>();\n if (bases.length > 0 && modelMap) {\n for (const field of allFields) {\n if (field.visibility === 'readonly') {\n for (const base of bases) {\n if (collectEffectiveWritableFieldNames(base, modelMap).has(field.name)) {\n fieldsToOmit.add(field.name);\n break;\n }\n }\n }\n }\n }\n const omitClause =\n fieldsToOmit.size > 0\n ? `.omit({ ${[...fieldsToOmit].map(f => `${quoteKey(f)}: true`).join(', ')} })`\n : '';\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => (modelsWithInput?.has(b) ? `${b}Input` : b));\n lines.push(`export const ${name}Input = ${head}${tail}${omitClause}.extend({`);\n } else {\n lines.push(`export const ${name}Input = ${wrapper}({`);\n }\n lines.push(...writeBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name}Input = z.infer<typeof ${name}Input>;`);\n\n return lines;\n}\n\n// ─── Fields ────────────────────────────────────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!caseTransform || caseTransform === 'camel') return name;\n if (caseTransform === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\nfunction renderFields(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderField(f, defaultMode));\n}\n\nfunction renderFieldsAsPascalCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const pascalKey = camelToPascal(f.name);\n let expr = renderType(f.type, 'pascal', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(pascalKey)}: ${expr},`;\n });\n}\n\nfunction renderFieldsAsSnakeCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const snakeKey = camelToSnake(f.name);\n let expr = renderType(f.type, 'snake', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n // .nullish() accepts null or undefined from the API; the transform coerces null → undefined\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(snakeKey)}: ${expr},`;\n });\n}\n\nfunction renderField(field: FieldNode, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderType(field.type, undefined, defaultMode);\n\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\n// ─── Type rendering ────────────────────────────────────────────────────────\n\n/**\n * Render a ContractKit AST type node as a Zod schema expression string.\n *\n * @param parseCaseTransform - When set, generates a `.transform()` that remaps incoming keys from\n * the given casing (`'snake'` | `'pascal'`) to camelCase for `inlineObject` types.\n * @param defaultMode - Fallback object mode (`'strict'` | `'strip'` | `'loose'`) when the node\n * doesn't specify its own mode.\n */\nexport function renderType(type: ContractTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderScalar(type);\n case 'array':\n return renderArray(type, parseCaseTransform, defaultMode);\n case 'tuple':\n return renderTuple(type);\n case 'record':\n return renderRecord(type);\n case 'enum':\n return renderEnum(type);\n case 'literal':\n return renderLiteral(type);\n case 'union':\n return renderUnion(type, parseCaseTransform, defaultMode);\n case 'discriminatedUnion':\n return renderDiscriminatedUnion(type, parseCaseTransform, defaultMode);\n case 'intersection':\n return renderIntersection(type, parseCaseTransform, defaultMode);\n case 'ref':\n return type.name;\n case 'lazy':\n return `z.lazy(() => ${renderType(type.inner, parseCaseTransform, defaultMode)})`;\n case 'inlineObject':\n return renderInlineObject(type, parseCaseTransform, defaultMode);\n default:\n return 'z.unknown()';\n }\n}\n\n/**\n * Render a regex source as a JS regex literal for `.regex(...)`. If the source already has\n * anchors (`^` at the start and/or an unescaped `$` at the end) we trust the user's intent\n * and emit it as-is; otherwise we wrap with `^...$` so contracts default to full-match\n * semantics. Forward slashes are always escaped since `/` is the literal delimiter.\n */\nfunction renderRegexLiteral(source: string): string {\n const body = source.replace(/\\//g, '\\\\/');\n if (regexHasAnchor(source)) return `/${body}/`;\n return `/^${body}$/`;\n}\n\nfunction regexHasAnchor(source: string): boolean {\n if (source.startsWith('^')) return true;\n if (!source.endsWith('$')) return false;\n // The trailing `$` is an anchor only if it isn't escaped — count immediately preceding\n // backslashes; an even count (including zero) means `$` is unescaped.\n let i = source.length - 2;\n let backslashes = 0;\n while (i >= 0 && source[i] === '\\\\') {\n backslashes++;\n i--;\n }\n return backslashes % 2 === 0;\n}\n\nfunction renderScalar(s: ScalarTypeNode): string {\n switch (s.name) {\n case 'string': {\n let e = 'z.string()';\n if (s.min !== undefined && s.max !== undefined) e += `.min(${s.min}).max(${s.max})`;\n else if (s.min !== undefined) e += `.min(${s.min})`;\n else if (s.max !== undefined) e += `.max(${s.max})`;\n if (s.len !== undefined) e += `.length(${s.len})`;\n if (s.regex) e += `.regex(${renderRegexLiteral(s.regex)})`;\n return e;\n }\n case 'number': {\n let e = 'z.coerce.number()';\n if (s.min !== undefined) e += `.min(${s.min})`;\n if (s.max !== undefined) e += `.max(${s.max})`;\n return e;\n }\n case 'int': {\n let e = 'z.coerce.number().int()';\n if (s.min !== undefined) e += `.min(${s.min})`;\n if (s.max !== undefined) e += `.max(${s.max})`;\n return e;\n }\n case 'bigint': {\n let inner = 'z.bigint()';\n if (s.min !== undefined) inner += `.min(${s.min}n)`;\n if (s.max !== undefined) inner += `.max(${s.max}n)`;\n return `z.preprocess((val) => typeof val === 'string' ? BigInt(val.replace(/n$/, '')) : val, ${inner})`;\n }\n case 'boolean':\n return `z.preprocess((v) => v === 'true' ? true : v === 'false' ? false : v, z.boolean())`;\n case 'date': {\n const fmt = s.format ?? 'yyyy-MM-dd';\n return `z.preprocess((val) => typeof val === 'string' ? DateTime.fromFormat(val, '${escapeString(fmt)}') : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be a date in format ${escapeString(fmt)}' }))`;\n }\n case 'time': {\n const fmt = s.format ?? 'HH:mm:ss';\n return `z.preprocess((val) => typeof val === 'string' ? DateTime.fromFormat(val, '${escapeString(fmt)}') : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be a time in format ${escapeString(fmt)}' }))`;\n }\n case 'datetime':\n return '_ZodDatetime';\n case 'interval':\n return '_ZodInterval';\n case 'duration': {\n const validParts = [`val instanceof Duration && val.isValid`];\n if (s.min !== undefined) validParts.push(`val.toMillis() >= Duration.fromISO('${s.min}').toMillis()`);\n if (s.max !== undefined) validParts.push(`val.toMillis() <= Duration.fromISO('${s.max}').toMillis()`);\n const validation = validParts.join(' && ');\n let message = 'Must be an ISO 8601 duration';\n if (s.min !== undefined && s.max !== undefined) message += ` between ${s.min} and ${s.max}`;\n else if (s.min !== undefined) message += ` of at least ${s.min}`;\n else if (s.max !== undefined) message += ` of at most ${s.max}`;\n return `z.preprocess((val) => typeof val === 'string' ? Duration.fromISO(val) : val, z.custom<Duration>((val) => ${validation}, { message: '${message}' }))`;\n }\n case 'email':\n return 'z.email()';\n case 'url':\n return 'z.url()';\n case 'uuid':\n return 'z.uuid()';\n case 'unknown':\n return 'z.unknown()';\n case 'null':\n return 'z.null()';\n case 'object':\n return 'z.record(z.string(), z.unknown())';\n case 'binary':\n return '_ZodBinary';\n case 'json':\n return '_ZodJson';\n default:\n return 'z.unknown()';\n }\n}\n\nfunction renderArray(a: ArrayTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n let e = `z.array(${renderType(a.item, parseCaseTransform, defaultMode)})`;\n if (a.min !== undefined) e += `.min(${a.min})`;\n if (a.max !== undefined) e += `.max(${a.max})`;\n return e;\n}\n\nfunction renderTuple(t: TupleTypeNode): string {\n return `z.tuple([${t.items.map(i => renderType(i)).join(', ')}])`;\n}\n\nfunction renderRecord(r: RecordTypeNode): string {\n return `z.record(${renderType(r.key)}, ${renderType(r.value)})`;\n}\n\nfunction renderEnum(e: EnumTypeNode): string {\n const vals = e.values.map(v => `\"${v}\"`).join(', ');\n return `z.enum([${vals}])`;\n}\n\nfunction renderLiteral(l: LiteralTypeNode): string {\n if (typeof l.value === 'string') return `z.literal(\"${escapeString(l.value)}\")`;\n return `z.literal(${l.value})`;\n}\n\nfunction renderUnion(u: UnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.union([${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderDiscriminatedUnion(u: DiscriminatedUnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.discriminatedUnion(\"${escapeString(u.discriminator)}\", [${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderIntersection(i: IntersectionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const [first, ...rest] = i.members;\n // When the pattern is ref & (ref | inlineObject)*, use .extend() chains to\n // produce a single ZodObject. .and() breaks strict objects — each strict side\n // rejects the other side's keys during intersection parsing, and ZodIntersection\n // has no .strict() method.\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n expr += `.extend(${member.name}.shape)`;\n } else {\n const m = member as InlineObjectTypeNode;\n const fieldLines =\n parseCaseTransform === 'snake'\n ? renderFieldsAsSnakeCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : parseCaseTransform === 'pascal'\n ? renderFieldsAsPascalCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : m.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderType(first!, parseCaseTransform, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderType(member, parseCaseTransform, defaultMode)})`;\n }\n return expr;\n}\n\nfunction renderInlineObject(o: InlineObjectTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const wrapper = modeToWrapper(o.mode ?? defaultMode ?? 'strict');\n if (parseCaseTransform === 'snake') {\n const snakeLines = renderFieldsAsSnakeCase(o.fields, defaultMode);\n const joined = snakeLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const snakeKey = camelToSnake(f.name);\n // Optional fields use .nullish() on input; coerce null → undefined in output\n const val = f.optional ? `data.${snakeKey} ?? undefined` : `data.${snakeKey}`;\n return ` ${quoteKey(f.name)}: ${val},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n if (parseCaseTransform === 'pascal') {\n const pascalLines = renderFieldsAsPascalCase(o.fields, defaultMode);\n const joined = pascalLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const pascalKey = camelToPascal(f.name);\n const val = f.optional ? `data.${pascalKey} ?? undefined` : `data.${pascalKey}`;\n return ` ${quoteKey(f.name)}: ${val},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n const fields = o.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${wrapper}({\\n${fields}\\n})`;\n}\n\n// ─── Input type rendering ─────────────────────────────────────────────────\n\n/**\n * Like renderScalar, but coerces from string input (JSON wire format).\n * Used for Input (write) schemas where data arrives as JSON strings.\n */\nfunction renderInputScalar(s: ScalarTypeNode): string {\n return renderScalar(s);\n}\n\n/**\n * Like renderType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers, and coerces scalars from strings.\n * Used for Input (write) schema fields so that sub-type references also\n * point to their Input variants.\n */\nexport function renderInputType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderInputScalar(type);\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n let e = `z.array(${renderInputType(type.item, modelsWithInput, defaultMode)})`;\n if (type.min !== undefined) e += `.min(${type.min})`;\n if (type.max !== undefined) e += `.max(${type.max})`;\n return e;\n }\n case 'tuple':\n return `z.tuple([${type.items.map(i => renderInputType(i, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'record':\n return `z.record(${renderInputType(type.key, modelsWithInput, defaultMode)}, ${renderInputType(type.value, modelsWithInput, defaultMode)})`;\n case 'union':\n return `z.union([${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'discriminatedUnion':\n return `z.discriminatedUnion(\"${escapeString(type.discriminator)}\", [${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderInputField(f, modelsWithInput ?? new Set(), defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderInputType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderInputType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'lazy':\n return `z.lazy(() => ${renderInputType(type.inner, modelsWithInput, defaultMode)})`;\n case 'inlineObject': {\n const fields = type.fields\n .flatMap(f => renderInputField(f, modelsWithInput ?? new Set(), defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n default:\n return renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderInputType(field.type, modelsWithInput, defaultMode);\n\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\nfunction renderInputFields(fields: FieldNode[], modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderInputField(f, modelsWithInput, defaultMode));\n}\n\n// ─── Query type rendering ─────────────────────────────────────────────────\n\n/**\n * Like renderType, but wraps array types with z.preprocess to handle\n * query strings where a single value arrives as a string instead of a string[].\n * Also uses Input variants for model refs when modelsWithInput is provided.\n */\nexport function renderQueryType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'array': {\n const inner = modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n return `z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner})`;\n }\n case 'inlineObject': {\n const fields = type.fields.map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`).join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderQueryType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderQueryType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n default:\n return modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderQueryField(field: FieldNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n let expr =\n field.type.kind === 'array'\n ? renderQueryType(field.type, modelsWithInput, defaultMode)\n : modelsWithInput\n ? renderInputType(field.type, modelsWithInput, defaultMode)\n : renderType(field.type, undefined, defaultMode);\n\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n\n return `${quoteKey(field.name)}: ${expr},`;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\nfunction quoteKey(name: string): string {\n return isValidIdentifier(name) ? name : `'${name}'`;\n}\n\n// ─── String escaping ──────────────────────────────────────────────────────\n\nfunction escapeString(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r');\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction rootNeedsDateTime(root: ContractRootNode): boolean {\n return root.models.some(m => (m.type && typeNeedsDateTime(m.type)) || m.fields.some(f => typeNeedsDateTime(f.type)));\n}\n\n/** Returns true if `type` (recursively) contains a scalar with the given `name`. */\nexport function typeNeedsScalar(type: ContractTypeNode, name: string): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === name;\n case 'array':\n return typeNeedsScalar(type.item, name);\n case 'tuple':\n return type.items.some(i => typeNeedsScalar(i, name));\n case 'record':\n return typeNeedsScalar(type.key, name) || typeNeedsScalar(type.value, name);\n case 'union':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'discriminatedUnion':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'intersection':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'lazy':\n return typeNeedsScalar(type.inner, name);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsScalar(f.type, name));\n default:\n return false;\n }\n}\n\n/** Returns true if any model in `root` uses a scalar with the given `name`. */\nexport function rootNeedsScalar(root: ContractRootNode, name: string): boolean {\n return root.models.some(m => (m.type && typeNeedsScalar(m.type, name)) || m.fields.some(f => typeNeedsScalar(f.type, name)));\n}\n\n/** Returns true if `type` (recursively) contains a `date`, `time`, or `datetime` scalar. */\nexport function typeNeedsDateTime(type: ContractTypeNode): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === 'date' || type.name === 'time' || type.name === 'datetime';\n case 'array':\n return typeNeedsDateTime(type.item);\n case 'union':\n return type.members.some(typeNeedsDateTime);\n case 'discriminatedUnion':\n return type.members.some(typeNeedsDateTime);\n case 'intersection':\n return type.members.some(typeNeedsDateTime);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsDateTime(f.type));\n default:\n return false;\n }\n}\n\n/** Collect model names referenced in `root` that are not defined locally (need to be imported). */\nexport function collectExternalRefs(root: ContractRootNode): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (model.bases?.[0] && !localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n }\n\n for (const name of localNames) refs.delete(name);\n return [...refs].sort();\n}\n\n/** Collect external Input variant refs needed for Input schema fields. */\nexport function collectExternalInputRefs(root: ContractRootNode, modelsWithInput: Set<string>): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (!modelsWithInput.has(model.name)) continue;\n // Type alias: collect Input refs from the aliased type expression.\n if (model.type) {\n collectInputTypeRefs(model.type, refs, modelsWithInput);\n continue;\n }\n // When a model extends an external parent that has an Input variant,\n // the write schema extends ParentInput — so we need to import it.\n if (model.bases?.[0] && modelsWithInput.has(model.bases?.[0]) && !localNames.has(model.bases?.[0])) {\n refs.add(`${model.bases?.[0]}Input`);\n }\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n for (const field of writeFields) {\n collectInputTypeRefs(field.type, refs, modelsWithInput);\n }\n }\n\n // Remove locally defined Input variants (generated in this file)\n for (const name of localNames) {\n refs.delete(`${name}Input`);\n }\n\n return [...refs].sort();\n}\n\nfunction collectInputTypeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(i => collectInputTypeRefs(i, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeRefs(type.key, out, modelsWithInput);\n collectInputTypeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\n/**\n * Topologically sort models so dependencies are emitted before dependents.\n * Falls back to source order for cycles (which would need z.lazy at runtime).\n */\nexport function topoSortModels(models: ModelNode[]): ModelNode[] {\n const localNames = new Set(models.map(m => m.name));\n const modelMap = new Map(models.map(m => [m.name, m]));\n\n // Build adjacency: model name → set of local model names it depends on\n const deps = new Map<string, Set<string>>();\n for (const model of models) {\n const refs = new Set<string>();\n if (model.bases?.[0] && localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // Keep only local dependencies\n const localDeps = new Set<string>();\n for (const r of refs) {\n if (localNames.has(r) && r !== model.name) localDeps.add(r);\n }\n deps.set(model.name, localDeps);\n }\n\n // Kahn's algorithm\n const inDegree = new Map<string, number>();\n for (const name of localNames) inDegree.set(name, 0);\n for (const [, d] of deps) {\n for (const dep of d) {\n inDegree.set(dep, (inDegree.get(dep) ?? 0) + 1);\n }\n }\n\n // Note: inDegree counts how many models *depend on* this model,\n // but for Kahn's we need how many dependencies each model has.\n // Re-do: inDegree = number of unresolved deps for each model.\n const remaining = new Map<string, Set<string>>();\n for (const [name, d] of deps) {\n remaining.set(name, new Set(d));\n }\n\n const queue: string[] = [];\n for (const name of localNames) {\n if (remaining.get(name)!.size === 0) queue.push(name);\n }\n\n const sorted: ModelNode[] = [];\n while (queue.length > 0) {\n const name = queue.shift()!;\n sorted.push(modelMap.get(name)!);\n // Remove this model from all dependents' remaining sets\n for (const [other, rem] of remaining) {\n if (rem.delete(name) && rem.size === 0) {\n queue.push(other);\n }\n }\n }\n\n // Append any models not yet emitted (cycles)\n for (const model of models) {\n if (!sorted.includes(model)) sorted.push(model);\n }\n\n return sorted;\n}\n\n/**\n * Resolve the import path for an external model reference.\n * When a codegen context is available, computes the correct relative path\n * from the current file to the referenced model's output file.\n * Falls back to same-directory PascalCase → dot.case convention.\n */\nexport function resolveImportPath(refName: string, context?: ContractCodegenContext): string {\n if (context) {\n const refOutPath = context.modelOutPaths.get(refName);\n if (refOutPath) {\n const fromDir = dirname(context.currentOutPath);\n let rel = relative(fromDir, refOutPath);\n // Replace .ts extension with .js for ESM imports\n rel = rel.replace(/\\.ts$/, '.js');\n // Ensure relative path starts with ./ or ../\n if (!rel.startsWith('.')) rel = './' + rel;\n return rel;\n }\n }\n // Fallback: assume same directory, use PascalCase → dot.case convention\n const moduleName = pascalToDotCase(refName);\n return `./${moduleName}.js`;\n}\n\n/** Convert PascalCase to dot-separated lowercase: CounterpartyAccount → counterparty.account */\nexport function pascalToDotCase(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/g, '$1.$2').toLowerCase();\n}\n","import type { OpRootNode, OpRouteNode, OpOperationNode, ContractTypeNode, ParamSource, ObjectMode } from '@contractkit/core';\nimport { resolveModifiers, resolveSecurity, SECURITY_NONE, classifyContentType } from '@contractkit/core';\nimport {\n renderType,\n renderInputType,\n renderQueryType,\n pascalToDotCase,\n typeNeedsDateTime,\n typeNeedsScalar,\n modeToWrapper,\n} from './codegen-contract.js';\nimport { renderOutputTsType, quoteKey, headerNameToProperty } from './ts-render.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Content-type helpers ──────────────────────────────────────────────────\n\n/** Map a request MIME type to the koa-bodyparser parser token used in middleware. */\nfunction bodyParserToken(contentType: string): string {\n switch (classifyContentType(contentType)) {\n case 'urlencoded':\n return 'urlencoded';\n case 'multipart':\n return 'multipart';\n case 'text':\n return 'text';\n case 'binary':\n // koa-bodyparser has no native binary token; fall back to text so the body is\n // still readable as a string. Services handling binary uploads should switch to\n // multipart/form-data.\n return 'text';\n default:\n return 'json';\n }\n}\n\n/**\n * Deep structural equality on ContractTypeNode, ignoring source locations on inline fields.\n * Used to decide whether multiple declared request MIMEs can share a single validate path.\n */\nexport function bodyTypesStructurallyEqual(a: ContractTypeNode, b: ContractTypeNode): boolean {\n if (a.kind !== b.kind) return false;\n switch (a.kind) {\n case 'scalar': {\n const bb = b as typeof a;\n return a.name === bb.name && a.min === bb.min && a.max === bb.max && a.len === bb.len && a.regex === bb.regex && a.format === bb.format;\n }\n case 'array': {\n const bb = b as typeof a;\n return a.min === bb.min && a.max === bb.max && bodyTypesStructurallyEqual(a.item, bb.item);\n }\n case 'tuple': {\n const bb = b as typeof a;\n return a.items.length === bb.items.length && a.items.every((x, i) => bodyTypesStructurallyEqual(x, bb.items[i]!));\n }\n case 'record': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.key, bb.key) && bodyTypesStructurallyEqual(a.value, bb.value);\n }\n case 'enum': {\n const bb = b as typeof a;\n return a.values.length === bb.values.length && a.values.every((v, i) => v === bb.values[i]);\n }\n case 'literal': {\n const bb = b as typeof a;\n return a.value === bb.value;\n }\n case 'union':\n case 'intersection': {\n const bb = b as typeof a;\n return a.members.length === bb.members.length && a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!));\n }\n case 'discriminatedUnion': {\n const bb = b as typeof a;\n return (\n a.discriminator === bb.discriminator &&\n a.members.length === bb.members.length &&\n a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!))\n );\n }\n case 'ref': {\n const bb = b as typeof a;\n return a.name === bb.name && !!a.lazy === !!bb.lazy;\n }\n case 'lazy': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.inner, bb.inner);\n }\n case 'inlineObject': {\n const bb = b as typeof a;\n if (a.mode !== bb.mode) return false;\n if (a.fields.length !== bb.fields.length) return false;\n return a.fields.every((f, i) => {\n const g = bb.fields[i]!;\n return (\n f.name === g.name &&\n f.optional === g.optional &&\n f.nullable === g.nullable &&\n f.visibility === g.visibility &&\n f.default === g.default &&\n !!f.deprecated === !!g.deprecated &&\n bodyTypesStructurallyEqual(f.type, g.type)\n );\n });\n }\n }\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\nexport interface OpCodegenOptions {\n servicePathTemplate?: string;\n typeImportPathTemplate?: string;\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /**\n * Whether to emit handlers for operations marked `internal`. Defaults to `true` because\n * the server still needs routes for internal endpoints; set to `false` to omit them\n * from the generated router entirely.\n */\n includeInternal?: boolean;\n}\n\n/** Generate a Koa router module for every operation in `root`, including the imports, type aliases, and handler list. */\nexport function generateOp(root: OpRootNode, options: OpCodegenOptions = {}): string {\n // Collect all referenced types across all routes\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput);\n const services = collectServices(root);\n const routerName = deriveRouterName(root.file);\n const needsParseAndValidate = routeNeedsValidation(root);\n\n // Generate the body first so we can detect whether `z.` is actually referenced\n // before deciding whether to emit the zod import.\n const body: string[] = [];\n const needsSignature = fileNeedsSignature(root);\n const needsSecurity = fileNeedsSecurity(root);\n const koaImports = ['ServerKitRouter', 'bodyParserMiddleware'];\n if (needsSecurity) koaImports.push('requireSecurity');\n if (needsSignature) koaImports.push('requireSignature');\n body.push(`import { ${koaImports.join(', ')} } from '@maroonedsoftware/koa';`);\n\n for (const svc of services) {\n const modulePath = root.services?.[svc] ?? root.meta[svc] ?? deriveModulePath(svc, options.servicePathTemplate);\n body.push(`import { ${svc} } from '${modulePath}';`);\n }\n\n if (types.length > 0) {\n body.push(...generateTypeImports(types, root.file, options));\n }\n\n if (opNeedsDateTime(root)) {\n body.push(`import { DateTime } from 'luxon';`);\n }\n\n if (needsParseAndValidate) {\n body.push(`import { parseAndValidate } from '@maroonedsoftware/zod';`);\n }\n\n const helpers: string[] = [];\n if (opNeedsScalar(root, 'binary')) {\n helpers.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (opNeedsScalar(root, 'datetime')) {\n helpers.push(\n `const _ZodDatetime = z.preprocess((val) => typeof val === 'string' ? DateTime.fromISO(val) : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be in ISO 8601 format' }));`,\n );\n }\n if (opNeedsScalar(root, 'json')) {\n helpers.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n helpers.push(\n `const _ZodJson: z.ZodType<_JsonValue> = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(_ZodJson), z.record(z.string(), _ZodJson)]));`,\n );\n }\n\n const lines: string[] = [];\n\n lines.push('');\n lines.push('/**');\n const relFile = options.outPath ? relative(dirname(options.outPath), root.file) : root.file;\n lines.push(` * generated from [${basename(root.file)}](file://./${relFile})`);\n lines.push('*/');\n lines.push(`export const ${routerName} = ServerKitRouter();`);\n lines.push('');\n\n const includeInternal = options.includeInternal ?? true;\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n lines.push(...generateHandler(route, op, root, options));\n lines.push('');\n }\n }\n\n const allContent = [...body, ...(helpers.length ? ['', ...helpers] : []), ...lines].join('\\n');\n const needsZod = /\\bz\\./.test(allContent);\n return (needsZod ? `import { z } from 'zod';\\n` : '') + allContent;\n}\n\n// ─── Handler generation ────────────────────────────────────────────────────\n\nfunction generateHandler(route: OpRouteNode, op: OpOperationNode, root: OpRootNode, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const file = root.file;\n const outPath = options.outPath;\n const modelsWithInput = options.modelsWithInput;\n\n lines.push('/**');\n\n // JSDoc from description\n const desc = op.description ?? route.description;\n if (desc) {\n lines.push(` * ${desc}`);\n }\n // Source location comment\n const relFile = outPath ? relative(dirname(outPath), file) : file;\n lines.push(` * from [${basename(file)}](file://./${relFile}#L${op.loc.line})`);\n\n // Security annotation (operation-level wins; falls back to route → file level)\n const effectiveSecurity = resolveSecurity(route, op, root);\n if (effectiveSecurity === SECURITY_NONE) {\n lines.push(` * anonymous access, no security required`);\n }\n\n // Modifier annotations\n const mods = resolveModifiers(route, op);\n if (mods.includes('internal')) lines.push(` * @internal`);\n if (mods.includes('deprecated')) lines.push(` * @deprecated`);\n\n lines.push('*/');\n\n const method = op.method;\n const path = route.path.replace(/\\{(\\w+)\\}/g, ':$1');\n const bodies = op.request?.bodies ?? [];\n const hasBody = bodies.length > 0;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n\n // Middleware list\n const middlewares: string[] = [];\n if (effectiveSecurity !== SECURITY_NONE) {\n const args = effectiveSecurity && effectiveSecurity.requireMfa !== undefined ? `{ requireMfa: ${effectiveSecurity.requireMfa} }` : '';\n middlewares.push(`requireSecurity(${args})`);\n }\n if (hasBody) {\n const parserTokens = Array.from(new Set(bodies.map(b => bodyParserToken(b.contentType))));\n const tokensExpr = parserTokens.map(t => `'${t}'`).join(', ');\n middlewares.push(`bodyParserMiddleware([${tokensExpr}])`);\n }\n if (op.signature) {\n middlewares.push(`requireSignature('${op.signature}')`);\n }\n const middlewareStr = middlewares.length > 0 ? `, ${middlewares.join(', ')},` : ',';\n\n lines.push(`${deriveRouterName(file)}.${method}('${path}'${middlewareStr} async (ctx, next) => {`);\n\n // Params / query / headers validation (request-side — use Input variants)\n lines.push(...generateParamValidation(route.params, 'ctx.params', 'params', route.paramsMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.query, 'ctx.query', 'query', op.queryMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.headers, 'ctx.headers', 'headers', op.headersMode ?? 'strip', '', modelsWithInput));\n\n // Body validation (request-side — use Input variants)\n if (hasBody && op.request) {\n if (isSingleMultipart) {\n lines.push(` const multipartBody = ctx.body as MultipartBody;`);\n lines.push('');\n } else if (bodies.length === 1) {\n lines.push(` const body = await parseAndValidate(ctx.body, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n // All declared MIMEs share the same body shape — single validation suffices\n lines.push(` const body = await parseAndValidate(ctx.body, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else {\n // Different body types per MIME — dispatch on Content-Type\n const annotation = bodies\n .map(b =>\n b.contentType === 'multipart/form-data' ? 'MultipartBody' : `z.infer<typeof ${renderInputType(b.bodyType, modelsWithInput)}>`,\n )\n .join(' | ');\n lines.push(` let body!: ${annotation};`);\n lines.push(` switch (ctx.request.type) {`);\n for (const b of bodies) {\n lines.push(` case '${b.contentType}':`);\n if (b.contentType === 'multipart/form-data') {\n lines.push(` body = ctx.body as MultipartBody;`);\n } else {\n lines.push(` body = await parseAndValidate(ctx.body, ${renderInputType(b.bodyType, modelsWithInput)});`);\n }\n lines.push(` break;`);\n }\n lines.push(` }`);\n lines.push('');\n }\n }\n\n // Service call — use the first response with a body as the primary response\n const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];\n const serviceParts = inferService(op, route, file);\n const respHeaders = primaryResponse?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersAnnotation = hasRespHeaders\n ? `{ ${respHeaders\n .map(h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, options.modelsWithOutput)}`)\n .join('; ')} }`\n : '';\n\n if (primaryResponse?.bodyType) {\n const { annotation, prelude } = formatTypeAnnotation(primaryResponse.bodyType!, options.modelsWithOutput);\n if (prelude) {\n lines.push(` ${prelude}`);\n }\n lines.push(` const service = ctx.container.get(${serviceParts.className});`);\n if (hasRespHeaders) {\n lines.push(\n ` const result: { body: ${annotation}; headers: ${headersAnnotation} } = await service.${serviceParts.methodName}(${buildArgs(route, op)});`,\n );\n } else {\n lines.push(` const result: ${annotation} = await service.${serviceParts.methodName}(${buildArgs(route, op)});`);\n }\n } else {\n lines.push(` const service = ctx.container.get(${serviceParts.className});`);\n if (hasRespHeaders) {\n lines.push(` const result: { headers: ${headersAnnotation} } = await service.${serviceParts.methodName}(${buildArgs(route, op)});`);\n } else {\n lines.push(` await service.${serviceParts.methodName}(${buildArgs(route, op)});`);\n }\n }\n\n lines.push('');\n lines.push(` ctx.status = ${primaryResponse?.statusCode ?? 200};`);\n\n if (hasRespHeaders) {\n for (const h of respHeaders) {\n const accessor = `result.headers[${JSON.stringify(headerNameToProperty(h.name))}]`;\n if (h.optional) {\n lines.push(` if (${accessor} !== undefined) ctx.set('${h.name}', String(${accessor}));`);\n } else {\n lines.push(` ctx.set('${h.name}', String(${accessor}));`);\n }\n }\n }\n\n if (primaryResponse?.bodyType && primaryResponse.contentType) {\n lines.push(` ctx.type = '${primaryResponse.contentType}';`);\n lines.push(` ctx.body = ${hasRespHeaders ? 'result.body' : 'result'};`);\n }\n\n lines.push('');\n lines.push(` await next();`);\n lines.push(`});`);\n\n return lines;\n}\n\n// ─── Inference helpers ─────────────────────────────────────────────────────\n\nfunction inferService(op: OpOperationNode, route: OpRouteNode, file: string): { className: string; methodName: string } {\n // If explicitly declared: service: ServiceClass.methodName\n if (op.service) {\n const [cls = '', method] = op.service.split('.');\n return { className: cls, methodName: method ?? 'handle' };\n }\n\n // Infer from file name + method + path\n const baseName = deriveBaseName(file); // e.g. \"ledger.categories\" -> \"LedgerCategories\"\n const className = `${baseName}Service`;\n const methodName = inferMethodName(op.method, route.path);\n return { className, methodName };\n}\n\nfunction inferMethodName(method: string, path: string): string {\n const hasParam = path.includes('{');\n switch (method) {\n case 'get':\n return hasParam ? 'getById' : 'list';\n case 'post':\n return 'create';\n case 'put':\n return 'replace';\n case 'patch':\n return 'update';\n case 'delete':\n return 'delete';\n default:\n return 'handle';\n }\n}\n\nfunction buildArgs(route: OpRouteNode, op: OpOperationNode): string {\n const args: string[] = [];\n // Path params: spread individually (inline) or pass 'params' object (type-ref/ContractTypeNode)\n if (route.params) {\n if (route.params.kind === 'params') {\n args.push(...route.params.nodes.map(p => p.name));\n } else {\n args.push('params');\n }\n }\n // Body\n if (op.request && op.request.bodies.length > 0) {\n const bodies = op.request.bodies;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n args.push(isSingleMultipart ? 'multipartBody' : 'body');\n }\n // Query\n if (op.query) args.push('query');\n // Headers\n if (op.headers) args.push('headers');\n return args.join(', ');\n}\n\nfunction formatTypeAnnotation(bodyType: ContractTypeNode, modelsWithOutput?: Set<string>): { annotation: string; prelude?: string } {\n if (bodyType.kind === 'array') {\n const inner = formatTypeAnnotation(bodyType.item, modelsWithOutput);\n return { annotation: `${inner.annotation}[]`, prelude: inner.prelude };\n }\n if (bodyType.kind === 'ref') {\n const name = modelsWithOutput?.has(bodyType.name) ? `${bodyType.name}Output` : bodyType.name;\n return { annotation: name };\n }\n if (bodyType.kind === 'scalar') return { annotation: bodyType.name };\n // For complex types, extract schema into a variable so the result line stays readable\n const schema = renderType(bodyType);\n return {\n annotation: 'z.infer<typeof resultType>',\n prelude: `const resultType = ${schema};`,\n };\n}\n\nfunction generateParamValidation(\n source: ParamSource | undefined,\n ctxExpr: string,\n varName: string,\n mode: ObjectMode,\n suffix = '',\n modelsWithInput?: Set<string>,\n): string[] {\n if (!source) return [];\n const lines: string[] = [];\n const isQuery = ctxExpr === 'ctx.query';\n if (source.kind === 'ref') {\n // Type reference — apply mode as a method call on the schema\n const typeName = modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;\n lines.push(` const ${varName} = await parseAndValidate(${ctxExpr}, ${typeName}.${mode}());`);\n lines.push('');\n } else if (source.kind === 'params') {\n // Inline param declarations — wrap with the appropriate z.*Object constructor\n if (source.nodes.length > 0) {\n // Destructure only for params (spread individually in service call);\n // query/headers are passed as whole objects.\n const lhs = varName === 'params' ? `{ ${source.nodes.map(p => p.name).join(', ')} }` : varName;\n lines.push(` const ${lhs} = await parseAndValidate(`);\n lines.push(` ${ctxExpr},`);\n lines.push(` ${modeToWrapper(mode)}({`);\n for (const param of source.nodes) {\n const key = isValidIdentifier(param.name) ? param.name : `'${param.name}'`;\n if (isQuery && param.type.kind === 'array') {\n const inner = renderType(param.type);\n lines.push(` ${key}: z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner}),`);\n } else {\n lines.push(` ${key}: ${renderType(param.type)},`);\n }\n }\n lines.push(` })${suffix},`);\n lines.push(` );`);\n lines.push('');\n }\n } else {\n // ContractTypeNode — use query-aware rendering for query params (coerces single string → array),\n // otherwise use Input variant rendering; apply mode as a method call\n const schema = isQuery ? renderQueryType(source.node, modelsWithInput) : renderInputType(source.node, modelsWithInput);\n lines.push(` const ${varName} = await parseAndValidate(${ctxExpr}, (${schema}).${mode}());`);\n lines.push('');\n }\n return lines;\n}\n\n// ─── Type import resolution ────────────────────────────────────────────────\n\n/**\n * Generate per-file type import statements.\n * When modelOutPaths is available, groups types by their actual output file\n * and computes correct relative paths. Falls back to the template-based\n * single-import approach for types not found in the map.\n */\nfunction generateTypeImports(types: string[], opFile: string, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n // Group types by their output file\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n // Emit one import per source file with a relative path\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import { ${names.sort().join(', ')} } from '${rel}';`);\n }\n\n // Fallback for types not in the map\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import { ${type} } from './${moduleName}.js';`);\n }\n } else {\n // No resolution context — fall back to template-based single import\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\n// ─── Collection helpers ────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of route.operations) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n if (resp.bodyType) {\n collectTypeNodeRefs(resp.bodyType, types);\n collectOutputTypeNodeRefs(resp.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'tuple':\n type.items.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'record':\n collectOutputTypeNodeRefs(type.key, out, modelsWithOutput);\n collectOutputTypeNodeRefs(type.value, out, modelsWithOutput);\n break;\n case 'union':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'intersection':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'type') {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeNodeRefs(type.key, out, modelsWithInput);\n collectInputTypeNodeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\nfunction paramSourceNeedsDateTime(source: ParamSource | undefined): boolean {\n if (!source) return false;\n if (source.kind === 'ref') return false;\n if (source.kind === 'params') return source.nodes.some(p => typeNeedsDateTime(p.type));\n return typeNeedsDateTime(source.node);\n}\n\nfunction opNeedsDateTime(root: OpRootNode): boolean {\n return root.routes.some(\n route =>\n paramSourceNeedsDateTime(route.params) ||\n route.operations.some(\n op =>\n !!op.request?.bodies.some(b => typeNeedsDateTime(b.bodyType)) ||\n op.responses.some(r => r.bodyType && typeNeedsDateTime(r.bodyType)) ||\n paramSourceNeedsDateTime(op.query) ||\n paramSourceNeedsDateTime(op.headers),\n ),\n );\n}\n\nfunction paramSourceNeedsScalar(source: ParamSource | undefined, name: string): boolean {\n if (!source) return false;\n if (source.kind === 'ref') return false;\n if (source.kind === 'params') return source.nodes.some(p => typeNeedsScalar(p.type, name));\n return typeNeedsScalar(source.node, name);\n}\n\nfunction opNeedsScalar(root: OpRootNode, name: string): boolean {\n return root.routes.some(\n route =>\n paramSourceNeedsScalar(route.params, name) ||\n route.operations.some(\n op =>\n !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, name)) ||\n op.responses.some(r => r.bodyType && typeNeedsScalar(r.bodyType, name)) ||\n paramSourceNeedsScalar(op.query, name) ||\n paramSourceNeedsScalar(op.headers, name),\n ),\n );\n}\n\nfunction collectServices(root: OpRootNode): string[] {\n const services = new Set<string>();\n const inferredService = `${deriveBaseName(root.file)}Service`;\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (op.service) {\n services.add(op.service.split('.')[0] ?? op.service);\n } else {\n services.add(inferredService);\n }\n }\n }\n return [...services].sort();\n}\n\nfunction hasParamSource(source?: ParamSource): boolean {\n if (!source) return false;\n if (source.kind === 'ref') return true;\n if (source.kind === 'params') return source.nodes.length > 0;\n return true; // type\n}\n\nfunction routeNeedsValidation(root: OpRootNode): boolean {\n return root.routes.some(\n r => hasParamSource(r.params) || r.operations.some(op => !!op.request || hasParamSource(op.query) || hasParamSource(op.headers)),\n );\n}\n\nfunction fileNeedsSecurity(root: OpRootNode): boolean {\n return root.routes.some(route => route.operations.some(op => resolveSecurity(route, op, root) !== SECURITY_NONE));\n}\n\nfunction fileNeedsSignature(root: OpRootNode): boolean {\n return root.routes.some(route => route.operations.some(op => !!op.signature));\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\nfunction deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n // ledger.categories -> LedgerCategories\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction deriveRouterName(file: string): string {\n return `${deriveBaseName(file)}Router`;\n}\n\nfunction deriveModulePath(serviceName: string, template?: string): string {\n // LedgerService -> #modules/ledger/ledger.service.js\n const base = serviceName.replace(/Service$/, '');\n const kebab = base.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`).replace(/^-/, '');\n if (template) {\n return template.replace(/\\{name\\}/g, base).replace(/\\{kebab\\}/g, kebab);\n }\n return `#modules/${kebab}/${kebab}.service.js`;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n","import type { ContractTypeNode, FieldNode } from '@contractkit/core';\n\nexport const JSON_VALUE_TYPE_DECL = 'export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };';\n\nexport function quoteKey(name: string): string {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? name : `'${name}'`;\n}\n\n/** Convert an HTTP header name (e.g. `preference-applied`, `X-Request-ID`, `ETag`) to camelCase for use as a JS property. */\nexport function headerNameToProperty(name: string): string {\n const parts = name.split(/[-_]/).filter(Boolean);\n return parts\n .map((p, i) => {\n const lower = p.toLowerCase();\n return i === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);\n })\n .join('');\n}\n\n// ─── TypeScript type rendering ────────────────────────────────────────────\n\nexport function renderTsType(type: ContractTypeNode): string {\n switch (type.kind) {\n case 'scalar':\n return renderTsScalar(type.name);\n case 'array': {\n const inner = renderTsType(type.item);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'tuple':\n return `[${type.items.map(renderTsType).join(', ')}]`;\n case 'record':\n return `Record<${renderTsType(type.key)}, ${renderTsType(type.value)}>`;\n case 'enum':\n return type.values.map(v => `'${v}'`).join(' | ');\n case 'literal':\n return typeof type.value === 'string' ? `'${type.value}'` : String(type.value);\n case 'union':\n return type.members.map(renderTsType).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(renderTsType).join(' | ');\n case 'intersection':\n return type.members.map(renderTsType).join(' & ');\n case 'ref':\n return type.name;\n case 'lazy':\n return renderTsType(type.inner);\n case 'inlineObject':\n return renderTsInlineObject(type.fields);\n default:\n return 'unknown';\n }\n}\n\nfunction renderTsScalar(name: string): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n return 'string';\n case 'number':\n case 'int':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'datetime':\n case 'duration':\n case 'interval':\n return 'string';\n case 'null':\n return 'null';\n case 'unknown':\n return 'unknown';\n case 'object':\n return 'Record<string, unknown>';\n case 'binary':\n return 'Blob';\n case 'json':\n return 'JsonValue';\n default:\n return 'unknown';\n }\n}\n\nfunction renderTsInlineObject(fields: FieldNode[]): string {\n const entries = fields.map(f => {\n const opt = f.optional ? '?' : '';\n return `${quoteKey(f.name)}${opt}: ${renderTsType(f.type)}`;\n });\n return `{ ${entries.join('; ')} }`;\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers. Used for request-side types\n * (body, params, query, headers).\n */\nexport function renderInputTsType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {\n if (!modelsWithInput || modelsWithInput.size === 0) return renderTsType(type);\n switch (type.kind) {\n case 'ref':\n return modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n const inner = renderInputTsType(type.item, modelsWithInput);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' & ');\n case 'union':\n return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderInputTsType(f.type, modelsWithInput)}`).join('; ')} }`;\n case 'lazy':\n return renderInputTsType(type.inner, modelsWithInput);\n default:\n return renderTsType(type);\n }\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Output variant\n * (post-transform wire shape) when the model has format(output=...) or\n * transitively references one. Used for response-side types in routers\n * and SDK return types.\n */\nexport function renderOutputTsType(type: ContractTypeNode, modelsWithOutput?: Set<string>): string {\n if (!modelsWithOutput || modelsWithOutput.size === 0) return renderTsType(type);\n switch (type.kind) {\n case 'ref':\n return modelsWithOutput.has(type.name) ? `${type.name}Output` : type.name;\n case 'array': {\n const inner = renderOutputTsType(type.item, modelsWithOutput);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' & ');\n case 'union':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderOutputTsType(f.type, modelsWithOutput)}`).join('; ')} }`;\n case 'lazy':\n return renderOutputTsType(type.inner, modelsWithOutput);\n default:\n return renderTsType(type);\n }\n}\n","import type { OpRootNode, OpRouteNode, OpOperationNode, OpRequestBodyNode, ContractTypeNode, ParamSource } from '@contractkit/core';\nimport { resolveModifiers, isJsonMime, classifyContentType } from '@contractkit/core';\nimport { renderInputTsType, renderOutputTsType, quoteKey, headerNameToProperty, JSON_VALUE_TYPE_DECL } from './ts-render.js';\nimport { pascalToDotCase, typeNeedsScalar } from './codegen-contract.js';\nimport { bodyTypesStructurallyEqual } from './codegen-operation.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Body strategy ────────────────────────────────────────────────────────\n\ntype BodyStrategy =\n | { kind: 'none' }\n | { kind: 'single'; body: OpRequestBodyNode }\n | { kind: 'multi-equal'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-formdata-detect'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-required-arg'; bodies: OpRequestBodyNode[] };\n\n/** Serialize expression for a single MIME, given the source body var (e.g. 'body'). */\nfunction jsonOrFormSerialize(varName: string, contentType: string): string {\n if (contentType === 'application/x-www-form-urlencoded') {\n return `new URLSearchParams(${varName} as unknown as Record<string, string>).toString()`;\n }\n if (contentType === 'multipart/form-data') {\n return `(${varName} as FormData)`;\n }\n // application/json + any `+json` structured suffix — JSON.stringify with bigint support.\n return `JSON.stringify(${varName}, bigIntReplacer)`;\n}\n\n/**\n * Build a runtime expression that picks the right serialization based on a contentType variable.\n * Used by the SDK when the caller passes (or defaults to) a content-type at call time.\n */\nfunction renderSerializeExpr(varName: string, bodies: OpRequestBodyNode[], ctVar: string): string {\n // Build a chained ternary, last MIME is the fallback\n const arms = bodies.slice(0, -1);\n const last = bodies[bodies.length - 1]!;\n let expr = jsonOrFormSerialize(varName, last.contentType);\n for (let i = arms.length - 1; i >= 0; i--) {\n const arm = arms[i]!;\n expr = `${ctVar} === '${arm.contentType}' ? ${jsonOrFormSerialize(varName, arm.contentType)} : ${expr}`;\n }\n return expr;\n}\n\nfunction classifyBodyStrategy(op: OpOperationNode): BodyStrategy {\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 0) return { kind: 'none' };\n if (bodies.length === 1) return { kind: 'single', body: bodies[0]! };\n if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n return { kind: 'multi-equal', bodies };\n }\n if (bodies.some(b => b.contentType === 'multipart/form-data')) {\n return { kind: 'multi-formdata-detect', bodies };\n }\n return { kind: 'multi-required-arg', bodies };\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/** Options shared by every SDK code-generation entry point. */\nexport interface SdkCodegenOptions {\n /** Template for type import paths when `modelOutPaths` is not provided. Supports `{module}` and `{base}`. */\n typeImportPathTemplate?: string;\n /** Absolute path of the file currently being generated. Used to compute relative imports. */\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Absolute path to the shared sdk-options.ts file (if set, imports SdkOptions instead of defining inline) */\n sdkOptionsPath?: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /**\n * Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —\n * internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`\n * to include them (e.g. for an internal-use SDK).\n */\n includeInternal?: boolean;\n /**\n * Override the generated client class name. When omitted, falls back to\n * `deriveClientClassName(root.file)` (the legacy per-file name). The aggregator\n * uses this to emit `<Area><Subarea>Client` for area+subarea leaf files.\n */\n clientClassName?: string;\n}\n\n/**\n * Returns true if the root contains at least one operation eligible for SDK emission.\n * With `includeInternal: false` (default) that means at least one non-internal op; with\n * `includeInternal: true` any op qualifies.\n */\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\n/**\n * Generate a complete `*.client.ts` file for one operation root: imports, the client class\n * declaration, and one method per public operation. Used for top-level (no-area) files and\n * for subarea-leaf files. Area-level files are NOT routed through this — their methods get\n * inlined into the SDK aggregator via {@link generateClientMethods} + {@link generateSdkAggregator}.\n */\nexport function generateSdk(root: OpRootNode, options: SdkCodegenOptions = {}): string {\n const lines: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput, includeInternal);\n const clientClassName = options.clientClassName ?? deriveClientClassName(root.file);\n\n // Type-only imports\n if (types.length > 0) {\n lines.push(...generateTypeImports(types, root.file, options));\n }\n\n // SdkOptions import (from shared file) or inline fallback\n if (options.sdkOptionsPath && options.outPath) {\n let rel = relative(dirname(options.outPath), options.sdkOptionsPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const jsonImport = sdkNeedsJson(root, includeInternal) ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${rel}';`);\n const valueImports: string[] = [];\n if (sdkNeedsBigIntReplacer(root, includeInternal)) valueImports.push('bigIntReplacer');\n if (sdkNeedsBigIntReviver(root, includeInternal)) valueImports.push('parseJson');\n if (sdkNeedsQueryString(root, includeInternal)) valueImports.push('buildQueryString');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${rel}';`);\n }\n } else {\n lines.push('');\n lines.push('export class SdkError extends Error {');\n lines.push(' constructor(');\n lines.push(' public readonly status: number,');\n lines.push(' public readonly statusText: string,');\n lines.push(' public readonly body: unknown,');\n lines.push(' public readonly headers: Headers,');\n lines.push(' ) {');\n lines.push(' super(`${status} ${statusText}`);');\n lines.push(\" this.name = 'SdkError';\");\n lines.push(' }');\n lines.push('}');\n lines.push('');\n lines.push('export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;');\n lines.push('');\n lines.push('export interface SdkOptions {');\n lines.push(' baseUrl: string;');\n lines.push(' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);');\n lines.push(' fetch?: SdkFetch;');\n lines.push(' /** Called once per request to produce a unique X-Request-ID header value */');\n lines.push(' requestIdFactory?: () => string;');\n lines.push('}');\n lines.push('');\n lines.push('export function createSdkFetch(options: SdkOptions): SdkFetch {');\n lines.push(' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());');\n lines.push(' return async (url: string, init: RequestInit): Promise<Response> => {');\n lines.push(\" const baseHeaders = typeof options.headers === 'function'\");\n lines.push(' ? await options.headers()');\n lines.push(' : options.headers ?? {};');\n lines.push(' const res = await fetch(`${options.baseUrl}${url}`, {');\n lines.push(' ...init,');\n lines.push(\" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\");\n lines.push(' });');\n lines.push(' if (!res.ok) {');\n lines.push(' const text = await res.text();');\n lines.push(' let body: unknown;');\n lines.push(' try { body = JSON.parse(text); } catch { body = text; }');\n lines.push(' throw new SdkError(res.status, res.statusText, body, res.headers);');\n lines.push(' }');\n lines.push(' return res;');\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push('export function buildQueryString(query: object | undefined): string {');\n lines.push(' const searchParams = new URLSearchParams();');\n lines.push(' if (query) {');\n lines.push(' for (const [k, v] of Object.entries(query)) {');\n lines.push(' if (v === undefined || v === null) continue;');\n lines.push(' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }');\n lines.push(' else searchParams.set(k, String(v));');\n lines.push(' }');\n lines.push(' }');\n lines.push(' const qs = searchParams.toString();');\n lines.push(\" return qs ? `?${qs}` : '';\");\n lines.push('}');\n lines.push('');\n lines.push('export async function parseJson<T>(res: Response): Promise<T> {');\n lines.push(' return JSON.parse(await res.text(), bigIntReviver) as T;');\n lines.push('}');\n }\n\n if (sdkNeedsJson(root, includeInternal) && !(options.sdkOptionsPath && options.outPath)) {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n\n lines.push('');\n\n // Client class\n lines.push('/**');\n const relFile = options.outPath ? relative(dirname(options.outPath), root.file) : root.file;\n lines.push(` * generated from [${basename(root.file)}](file://./${relFile})`);\n lines.push(' */');\n lines.push(`export class ${clientClassName} {`);\n lines.push(' constructor(private fetch: SdkFetch) {}');\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n lines.push('');\n if (mods.includes('deprecated')) lines.push(' /** @deprecated */');\n lines.push(...generateMethod(route, op, root.file, options));\n }\n }\n\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Render the method-block lines for an operation file as if they were declared inside a\n * client class. Returns one consolidated array of strings (each pre-indented for class body\n * level, with leading blank lines between methods) plus the set of method names emitted —\n * the caller uses the names to detect cross-file collisions when multiple files contribute\n * to the same area-level client.\n *\n * Skips operations marked `internal` unless `options.includeInternal` is set.\n */\nexport function generateClientMethods(\n root: OpRootNode,\n options: SdkCodegenOptions,\n): { lines: string[]; methodNames: string[] } {\n const lines: string[] = [];\n const methodNames: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n lines.push('');\n if (mods.includes('deprecated')) lines.push(' /** @deprecated */');\n lines.push(...generateMethod(route, op, root.file, options));\n methodNames.push(deriveMethodName(op, route));\n }\n }\n return { lines, methodNames };\n}\n\n// ─── Method generation ────────────────────────────────────────────────────\n\nfunction generateMethod(route: OpRouteNode, op: OpOperationNode, file: string, options: SdkCodegenOptions): string[] {\n const lines: string[] = [];\n const methodName = deriveMethodName(op, route);\n const httpMethod = op.method.toUpperCase();\n const { modelsWithInput, modelsWithOutput } = options;\n\n // Build method parameters (request-side — use Input variants)\n const params = buildMethodParams(route, op, modelsWithInput);\n const paramStr = params.map(p => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ');\n\n // Determine return type — response side uses Output variants (post-transform wire shape).\n // For non-JSON responses the schema is ignored: text/* is read as string, binary as Blob.\n const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];\n const isVoid = !primaryResponse?.bodyType;\n const respCategory = primaryResponse?.contentType ? classifyContentType(primaryResponse.contentType) : 'json';\n const dataType = isVoid\n ? 'void'\n : respCategory === 'text'\n ? 'string'\n : respCategory === 'binary'\n ? 'Blob'\n : renderOutputTsType(primaryResponse!.bodyType!, modelsWithOutput);\n const respHeaders = primaryResponse?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersShape = hasRespHeaders\n ? `{ ${respHeaders.map(h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput)}`).join('; ')} }`\n : '';\n const returnType = hasRespHeaders ? (isVoid ? `{ headers: ${headersShape} }` : `{ data: ${dataType}; headers: ${headersShape} }`) : dataType;\n\n // JSDoc\n const desc = op.description ?? route.description;\n if (op.name || desc) {\n const tags: string[] = [];\n if (op.name) tags.push(`@name ${op.name}`);\n if (desc) tags.push(`@description ${desc}`);\n if (tags.length === 1) {\n lines.push(` /** ${tags[0]} */`);\n } else {\n lines.push(` /**`);\n for (const tag of tags) lines.push(` * ${tag}`);\n lines.push(` */`);\n }\n }\n\n lines.push(` async ${methodName}(${paramStr}): Promise<${returnType}> {`);\n\n // Build URL with path params\n const urlExpr = buildUrlExpression(route.path, route.params);\n\n // Query string\n const hasQuery = !!op.query;\n let fetchUrl = urlExpr;\n if (hasQuery) {\n lines.push(` const qs = buildQueryString(query);`);\n fetchUrl = urlExpr;\n }\n\n // Build fetch options\n const strategy = classifyBodyStrategy(op);\n const hasBody = strategy.kind !== 'none';\n const hasOpHeaders = !!op.headers;\n\n // Pre-emit serialization preludes for multi-MIME strategies\n if (strategy.kind === 'multi-equal') {\n const defaultCt = strategy.bodies[0]!.contentType;\n lines.push(` const __contentType = options?.contentType ?? '${defaultCt}';`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n } else if (strategy.kind === 'multi-formdata-detect') {\n lines.push(` const __isFormData = body instanceof FormData;`);\n const nonMultipart = strategy.bodies.find(b => b.contentType !== 'multipart/form-data')!;\n lines.push(` const __contentType: string = __isFormData ? 'multipart/form-data' : '${nonMultipart.contentType}';`);\n lines.push(\n ` const __serialized: BodyInit = __isFormData ? (body as FormData) : ${jsonOrFormSerialize('body', nonMultipart.contentType)};`,\n );\n } else if (strategy.kind === 'multi-required-arg') {\n lines.push(` const __contentType = options.contentType;`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n }\n\n const fetchArgs: string[] = [];\n\n if (hasQuery) {\n fetchArgs.push(`url: \\`${fetchUrl}\\${qs}\\``);\n } else {\n fetchArgs.push(`url: \\`${fetchUrl}\\``);\n }\n\n fetchArgs.push(`method: '${httpMethod}'`);\n\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n // FormData supplies its own Content-Type with boundary; don't override it.\n fetchArgs.push('body: body');\n } else if (cat === 'urlencoded') {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: new URLSearchParams(body as unknown as Record<string, string>).toString()');\n } else if (cat === 'text' || cat === 'binary') {\n // text/* and binary mimes pass the body through to fetch as-is — no schema serialization.\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: body');\n } else {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: JSON.stringify(body, bigIntReplacer)');\n }\n } else if (hasBody) {\n // multi-equal | multi-formdata-detect | multi-required-arg — share a __contentType / __serialized prelude\n fetchArgs.push(`headers: { 'Content-Type': __contentType }`);\n fetchArgs.push('body: __serialized');\n }\n\n if (hasOpHeaders) {\n const lastHeaderIdx = fetchArgs.findIndex(a => a.startsWith('headers:'));\n if (lastHeaderIdx !== -1) {\n const existing = fetchArgs[lastHeaderIdx]!;\n const inner = existing.slice('headers: '.length).replace(/^\\{\\s*|\\s*\\}$/g, '');\n fetchArgs[lastHeaderIdx] = `headers: { ${inner}, ...customHeaders }`;\n } else {\n fetchArgs.push('headers: customHeaders');\n }\n }\n\n const resultPrefix = isVoid && !hasRespHeaders ? '' : 'const result = ';\n if (fetchArgs.length === 2 && !hasBody && !hasOpHeaders && !hasQuery) {\n // Simple case — inline\n lines.push(` ${resultPrefix}await this.fetch(\\`${fetchUrl}\\`, { method: '${httpMethod}' });`);\n } else {\n lines.push(` ${resultPrefix}await this.fetch(${fetchArgs[0]!.split(': ').slice(1).join(': ')}, {`);\n for (let i = 1; i < fetchArgs.length; i++) {\n lines.push(` ${fetchArgs[i]},`);\n }\n lines.push(` });`);\n }\n\n const readBodyExpr =\n respCategory === 'text' ? `await result.text()` : respCategory === 'binary' ? `await result.blob()` : `await parseJson<${dataType}>(result)`;\n\n if (hasRespHeaders) {\n const headerEntries = respHeaders\n .map(h => `${quoteKey(headerNameToProperty(h.name))}: result.headers.get('${h.name}') ?? undefined`)\n .join(', ');\n if (isVoid) {\n lines.push(` return { headers: { ${headerEntries} } };`);\n } else {\n lines.push(` const data = ${readBodyExpr};`);\n lines.push(` return { data, headers: { ${headerEntries} } };`);\n }\n } else if (!isVoid) {\n lines.push(` return ${readBodyExpr};`);\n }\n\n lines.push(' }');\n\n return lines;\n}\n\n// ─── URL building ─────────────────────────────────────────────────────────\n\nfunction buildUrlExpression(path: string, _?: ParamSource): string {\n // Replace {paramName} with ${encodeURIComponent(paramName)}\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, (_match, name) => {\n return `\\${encodeURIComponent(${name})}`;\n });\n}\n\n// ─── Method parameters ────────────────────────────────────────────────────\n\ninterface MethodParam {\n name: string;\n type: string;\n optional: boolean;\n}\n\nfunction buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {\n const params: MethodParam[] = [];\n\n // Path params — always first, always required (request-side — use Input variants)\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const p of route.params.nodes) {\n params.push({ name: p.name, type: renderInputTsType(p.type, modelsWithInput), optional: false });\n }\n } else if (route.params.kind === 'ref') {\n const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;\n params.push({ name: 'params', type: typeName, optional: false });\n } else {\n params.push({ name: 'params', type: renderInputTsType(route.params.node, modelsWithInput), optional: false });\n }\n }\n\n // Body (request-side — use Input variants)\n const strategy = classifyBodyStrategy(op);\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n params.push({ name: 'body', type: 'FormData', optional: false });\n } else if (cat === 'text') {\n params.push({ name: 'body', type: 'string', optional: false });\n } else if (cat === 'binary') {\n params.push({ name: 'body', type: 'Blob | ArrayBuffer | Uint8Array | string', optional: false });\n } else {\n params.push({ name: 'body', type: renderInputTsType(body.bodyType, modelsWithInput), optional: false });\n }\n } else if (strategy.kind === 'multi-equal') {\n const bodies = strategy.bodies;\n const bodyType = renderInputTsType(bodies[0]!.bodyType, modelsWithInput);\n params.push({ name: 'body', type: bodyType, optional: false });\n const ctUnion = bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType?: ${ctUnion} }`, optional: true });\n } else if (strategy.kind === 'multi-formdata-detect') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n } else if (strategy.kind === 'multi-required-arg') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n const ctUnion = strategy.bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType: ${ctUnion} }`, optional: false });\n }\n\n // Query (request-side — use Input variants)\n if (op.query) {\n if (op.query.kind === 'params') {\n const fields = op.query.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');\n params.push({ name: 'query', type: `{ ${fields} }`, optional: true });\n } else if (op.query.kind === 'ref') {\n const typeName = modelsWithInput?.has(op.query.name) ? `${op.query.name}Input` : op.query.name;\n params.push({ name: 'query', type: typeName, optional: true });\n } else {\n params.push({ name: 'query', type: renderInputTsType(op.query.node, modelsWithInput), optional: true });\n }\n }\n\n // Headers (request-side — use Input variants)\n if (op.headers) {\n if (op.headers.kind === 'params') {\n const fields = op.headers.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');\n params.push({ name: 'customHeaders', type: `{ ${fields} }`, optional: true });\n } else if (op.headers.kind === 'ref') {\n const typeName = modelsWithInput?.has(op.headers.name) ? `${op.headers.name}Input` : op.headers.name;\n params.push({ name: 'customHeaders', type: typeName, optional: true });\n } else {\n params.push({ name: 'customHeaders', type: renderInputTsType(op.headers.node, modelsWithInput), optional: true });\n }\n }\n\n return params;\n}\n\n// ─── Method name inference ────────────────────────────────────────────────\n\nfunction deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {\n if (op.sdk) return op.sdk;\n if (op.name) return nameToMethodName(op.name);\n return inferMethodName(op.method, route.path);\n}\n\nfunction nameToMethodName(name: string): string {\n const parts = name.split(/[\\s\\-_]+/).filter(Boolean);\n return parts.map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join('');\n}\n\nfunction inferMethodName(method: string, path: string): string {\n // Build a name from the path segments + method\n // e.g. GET /users/:id → getUsersById\n // e.g. POST /users → postUsers\n // e.g. DELETE /users/:id → deleteUsersById\n const segments = path.split('/').filter(s => s.length > 0);\n const parts: string[] = [method.toLowerCase()];\n\n for (const seg of segments) {\n if (seg.startsWith('{')) {\n // {id} → ById, {accountId} → ByAccountId\n const paramName = seg.slice(1, -1);\n parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));\n } else {\n // Regular segment — camelCase it\n const segParts = seg.split(/[.-]/).filter(Boolean);\n for (const sp of segParts) {\n parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));\n }\n }\n }\n\n return parts[0]! + parts.slice(1).join('');\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\nfunction deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\n/** Derive a client class name from a `.ck` file path, e.g. `users.ck` → `UsersClient`. Used for legacy flat (no-area) files. */\nexport function deriveClientClassName(file: string): string {\n return `${deriveBaseName(file)}Client`;\n}\n\n/** Camel-cased property name for a flat client on the SDK aggregator, e.g. `users.ck` → `users`. */\nexport function deriveClientPropertyName(file: string): string {\n const base = deriveBaseName(file);\n return base.charAt(0).toLowerCase() + base.slice(1);\n}\n\n/**\n * Pull `area` / `subarea` from a file's `root.meta` (set via `options { keys: { ... } }`).\n * Both are optional. `area` drives top-level SDK grouping; `subarea` drives nesting under\n * an area's client class.\n */\nexport function getAreaSubarea(root: OpRootNode): { area?: string; subarea?: string } {\n return { area: root.meta?.area, subarea: root.meta?.subarea };\n}\n\nfunction pascal(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction camel(value: string): string {\n const p = pascal(value);\n return p.charAt(0).toLowerCase() + p.slice(1);\n}\n\n/** Class name for the area-level client, e.g. `area=identity` → `IdentityClient`. */\nexport function deriveAreaClientClassName(area: string): string {\n return `${pascal(area)}Client`;\n}\n\n/** Property name on the SDK aggregator for an area, e.g. `area=identity` → `identity`. */\nexport function deriveAreaPropertyName(area: string): string {\n return camel(area);\n}\n\n/** Class name for a leaf subarea client, e.g. `(identity, invitations)` → `IdentityInvitationsClient`. */\nexport function deriveSubareaClientClassName(area: string, subarea: string): string {\n return `${pascal(area)}${pascal(subarea)}Client`;\n}\n\n/** Property name on the area client for a subarea, e.g. `subarea=invitations` → `invitations`. */\nexport function deriveSubareaPropertyName(subarea: string): string {\n return camel(subarea);\n}\n\n// ─── Type collection ──────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>, includeInternal = false): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n const publicOps = route.operations.filter(op => includeInternal || !resolveModifiers(route, op).includes('internal'));\n if (publicOps.length === 0) continue;\n // Only collect path-param types if there are public ops on this route\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of publicOps) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n if (resp.bodyType) {\n collectTypeNodeRefs(resp.bodyType, types);\n collectOutputTypeNodeRefs(resp.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectOutputTypeNodeRefs(m, out, modelsWithOutput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectInputTypeNodeRefs(param.type, out, modelsWithInput);\n }\n } else {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeNodeRefs(m, out, modelsWithInput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** True if any emitted operation has query params (drives the `buildQueryString` import). */\nfunction sdkNeedsQueryString(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')) continue;\n if (op.query) return true;\n }\n }\n return false;\n}\n\n/** True if any emitted operation serializes a JSON request body (uses bigIntReplacer). */\nfunction sdkNeedsBigIntReplacer(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')) continue;\n if (op.request && op.request.bodies.some(b => isJsonMime(b.contentType))) return true;\n }\n }\n return false;\n}\n\n/** True if any public operation parses a JSON response body (uses bigIntReviver). */\nfunction sdkNeedsBigIntReviver(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')) continue;\n if (\n op.responses.some(r => {\n if (!r.bodyType) return false;\n // Only JSON-shaped responses use parseJson — text/binary read raw.\n return !r.contentType || classifyContentType(r.contentType) === 'json';\n })\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction sdkNeedsJson(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')) continue;\n const check = (src: ParamSource | undefined) => {\n if (!src || src.kind === 'ref') return false;\n if (src.kind === 'params') return src.nodes.some(p => typeNeedsScalar(p.type, 'json'));\n return typeNeedsScalar(src.node, 'json');\n };\n if (\n !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, 'json')) ||\n op.responses.some(r => r.bodyType && typeNeedsScalar(r.bodyType, 'json')) ||\n check(op.query) ||\n check(op.headers) ||\n check(route.params)\n )\n return true;\n }\n }\n return false;\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\n// ─── Type import resolution ───────────────────────────────────────────────\n\nfunction generateTypeImports(types: string[], opFile: string, options: SdkCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import type { ${names.sort().join(', ')} } from '${rel}';`);\n }\n\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import type { ${type} } from './${moduleName}.js';`);\n }\n } else {\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import type { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n\n// ─── Shared SDK files ──────────────────────────────────────────────────────\n\n/** Generate the shared SdkOptions interface file. */\nexport function generateSdkOptions(): string {\n return [\n 'export class SdkError extends Error {',\n ' constructor(',\n ' public readonly status: number,',\n ' public readonly statusText: string,',\n ' public readonly body: unknown,',\n ' public readonly headers: Headers,',\n ' ) {',\n ' super(`${status} ${statusText}`);',\n \" this.name = 'SdkError';\",\n ' }',\n '}',\n '',\n 'export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;',\n '',\n 'export interface SdkOptions {',\n ' baseUrl: string;',\n ' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);',\n ' fetch?: SdkFetch;',\n ' /** Called once per request to produce a unique X-Request-ID header value */',\n ' requestIdFactory?: () => string;',\n '}',\n '',\n 'export const bigIntReplacer = (_: string, value: any): any => {',\n \" if (typeof value === 'bigint') {\",\n \" return value.toString() + 'n';\",\n ' }',\n ' return value;',\n '};',\n '',\n 'export const bigIntReviver = (_: string, value: any): any => {',\n \" if (typeof value === 'string' && /^-?\\\\d+n$/.test(value)) {\",\n ' return BigInt(value.slice(0, -1));',\n ' }',\n ' return value;',\n '};',\n '',\n JSON_VALUE_TYPE_DECL,\n '',\n 'export function createSdkFetch(options: SdkOptions): SdkFetch {',\n ' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());',\n ' return async (url: string, init: RequestInit): Promise<Response> => {',\n \" const baseHeaders = typeof options.headers === 'function'\",\n ' ? await options.headers()',\n ' : options.headers ?? {};',\n ' const res = await fetch(`${options.baseUrl}${url}`, {',\n ' ...init,',\n \" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\",\n ' });',\n ' if (!res.ok) {',\n ' const text = await res.text();',\n ' let body: unknown;',\n ' try { body = JSON.parse(text); } catch { body = text; }',\n ' throw new SdkError(res.status, res.statusText, body, res.headers);',\n ' }',\n ' return res;',\n ' };',\n '}',\n '',\n 'export function buildQueryString(query: object | undefined): string {',\n ' const searchParams = new URLSearchParams();',\n ' if (query) {',\n ' for (const [k, v] of Object.entries(query)) {',\n ' if (v === undefined || v === null) continue;',\n ' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }',\n ' else searchParams.set(k, String(v));',\n ' }',\n ' }',\n ' const qs = searchParams.toString();',\n \" return qs ? `?${qs}` : '';\",\n '}',\n '',\n 'export async function parseJson<T>(res: Response): Promise<T> {',\n ' return JSON.parse(await res.text(), bigIntReviver) as T;',\n '}',\n '',\n ].join('\\n');\n}\n\n/**\n * Reference to a per-file leaf client emitted to its own `*.client.ts`. Used by the\n * aggregator to import the class and wire it as either a top-level `sdk.<prop>` or a\n * nested `sdk.<area>.<subarea>` property.\n */\nexport interface SdkClientInfo {\n /** Client class name (e.g. `UsersClient`, `IdentityInvitationsClient`). */\n className: string;\n /** Property name to expose this client under (e.g. `users`, `invitations`). */\n propertyName: string;\n /** Module specifier for the leaf file, relative to `sdk.ts` and `.js`-suffixed. */\n importPath: string;\n}\n\n/**\n * One area-level (no-subarea) `.ck` file whose methods are merged into the area's\n * `<Area>Client` (emitted to its own `<area>.client.ts`).\n */\nexport interface SdkAreaInlineFile {\n /** Parsed AST. */\n root: OpRootNode;\n /** Codegen options for this file (must have `outPath` pointing at the area client file so type-import paths resolve correctly). */\n codegenOptions: SdkCodegenOptions;\n}\n\n/** A grouping of files that share the same `keys.area`. */\nexport interface SdkAreaInfo {\n area: string;\n /**\n * Reference to the `<Area>Client` class — the file that holds it lives at\n * `client.importPath` (relative to `sdk.ts`) and is generated separately by\n * {@link generateAreaClient}. The aggregator just imports it.\n */\n client: SdkClientInfo;\n}\n\nexport interface SdkAggregatorInput {\n /** Files with no `keys.area` — kept as flat `Sdk.<filename>` properties (legacy behavior). */\n topLevelClients: SdkClientInfo[];\n /** One entry per `keys.area`. */\n areas: SdkAreaInfo[];\n /** Path to `sdk-options.ts` to import `SdkOptions`/`createSdkFetch`/etc. from. */\n sdkOptionsImportPath?: string;\n /** Name of the top-level aggregator class. Defaults to `Sdk`. */\n sdkClassName?: string;\n}\n\n/** Inputs to {@link generateAreaClient}. */\nexport interface AreaClientInput {\n /** Area name (e.g. `payments`). Drives the generated class name (`PaymentsClient`). */\n area: string;\n /** Output path of the generated `<area>.client.ts` file. Used to resolve relative type / leaf-client / sdk-options imports. */\n outPath: string;\n /** Files contributing inlined methods to the area client (typically area-level files with no subarea). */\n inlineFiles: SdkAreaInlineFile[];\n /** Subarea leaf clients exposed as named properties on the area client. */\n subareaClients: { propertyName: string; client: SdkClientInfo }[];\n /** Path to `sdk-options.ts`, used for `SdkFetch` and runtime helpers. */\n sdkOptionsPath: string;\n}\n\n/**\n * Generate a complete `<area>.client.ts` file: the `<Area>Client` class with\n * subarea property fields, a constructor that wires them, and inlined methods\n * merged from every area-level file in `inlineFiles`.\n *\n * Emitted by the plugin alongside the per-leaf `*.client.ts` files. The SDK\n * aggregator just imports the resulting class — see {@link generateSdkAggregator}.\n *\n * @throws if two area-level files contribute the same method name to the area —\n * disambiguate via `sdk:` on the operation, or move one into a subarea.\n */\nexport function generateAreaClient(input: AreaClientInput): string {\n const { area, outPath, inlineFiles, subareaClients, sdkOptionsPath } = input;\n const className = deriveAreaClientClassName(area);\n\n // ── Merge inputs across all inline files ────────────────────────────────\n const collectedMethodLines: string[] = [];\n const seenMethods = new Set<string>();\n const typesByImportPath = new Map<string, Set<string>>();\n const unresolvedTypes = new Set<string>();\n let needsJson = false;\n let needsBigIntReplacer = false;\n let needsBigIntReviver = false;\n let needsQueryString = false;\n\n for (const inline of inlineFiles) {\n const includeInternal = inline.codegenOptions.includeInternal ?? false;\n const { lines: methodLines, methodNames } = generateClientMethods(inline.root, inline.codegenOptions);\n for (const name of methodNames) {\n if (seenMethods.has(name)) {\n throw new Error(\n `[sdk] duplicate method '${name}' in area '${area}': two area-level files contribute the same method. Disambiguate via 'sdk:' or move one into a subarea.`,\n );\n }\n seenMethods.add(name);\n }\n collectedMethodLines.push(...methodLines);\n if (sdkNeedsJson(inline.root, includeInternal)) needsJson = true;\n if (sdkNeedsBigIntReplacer(inline.root, includeInternal)) needsBigIntReplacer = true;\n if (sdkNeedsBigIntReviver(inline.root, includeInternal)) needsBigIntReviver = true;\n if (sdkNeedsQueryString(inline.root, includeInternal)) needsQueryString = true;\n\n // Resolve each file's type refs against THIS file's modelOutPaths, but\n // produce import paths relative to the area client's outPath (not the\n // contributing file's outPath, which pointed at the now-defunct sdk.ts).\n const typesForFile = collectTypes(\n inline.root,\n inline.codegenOptions.modelsWithInput,\n inline.codegenOptions.modelsWithOutput,\n includeInternal,\n );\n const { modelOutPaths } = inline.codegenOptions;\n if (modelOutPaths) {\n const fromDir = dirname(outPath);\n for (const t of typesForFile) {\n const typeOutPath = modelOutPaths.get(t);\n if (typeOutPath) {\n let rel = relative(fromDir, typeOutPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const set = typesByImportPath.get(rel) ?? new Set();\n set.add(t);\n typesByImportPath.set(rel, set);\n } else {\n unresolvedTypes.add(t);\n }\n }\n }\n }\n\n // ── Imports ─────────────────────────────────────────────────────────────\n let sdkOptionsRel = relative(dirname(outPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!sdkOptionsRel.startsWith('.')) sdkOptionsRel = './' + sdkOptionsRel;\n\n const lines: string[] = [];\n const jsonImport = needsJson ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${sdkOptionsRel}';`);\n const valueImports: string[] = [];\n if (needsBigIntReplacer) valueImports.push('bigIntReplacer');\n if (needsBigIntReviver) valueImports.push('parseJson');\n if (needsQueryString) valueImports.push('buildQueryString');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${sdkOptionsRel}';`);\n }\n\n for (const path of [...typesByImportPath.keys()].sort()) {\n const names = [...typesByImportPath.get(path)!].sort();\n lines.push(`import type { ${names.join(', ')} } from '${path}';`);\n }\n for (const t of [...unresolvedTypes].sort()) {\n lines.push(`import type { ${t} } from './${pascalToDotCase(t)}.js';`);\n }\n\n // Leaf client imports (subareas only — top-level clients live next to sdk.ts).\n const importedClients = new Set<string>();\n for (const sc of subareaClients) {\n const key = `${sc.client.className}|${sc.client.importPath}`;\n if (importedClients.has(key)) continue;\n importedClients.add(key);\n lines.push(`import { ${sc.client.className} } from '${sc.client.importPath}';`);\n }\n lines.push('');\n\n // ── <Area>Client class ──────────────────────────────────────────────────\n lines.push(`export class ${className} {`);\n for (const sc of subareaClients) {\n lines.push(` readonly ${sc.propertyName}: ${sc.client.className};`);\n }\n if (subareaClients.length > 0) lines.push('');\n if (collectedMethodLines.length > 0 || subareaClients.length > 0) {\n const fetchModifier = collectedMethodLines.length > 0 ? 'private ' : '';\n lines.push(` constructor(${fetchModifier}fetch: SdkFetch) {`);\n for (const sc of subareaClients) {\n lines.push(` this.${sc.propertyName} = new ${sc.client.className}(fetch);`);\n }\n lines.push(' }');\n }\n for (const ln of collectedMethodLines) lines.push(ln);\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the SDK aggregator (`sdk.ts`) — the entry-point file consumers import.\n *\n * Imports every `<Area>Client` (one per area, generated by {@link generateAreaClient}\n * to its own `<area>.client.ts`) and every leaf top-level client, then emits a\n * `class Sdk` that exposes them as properties.\n */\nexport function generateSdkAggregator(input: SdkAggregatorInput): string {\n const sdkOptionsImportPath = input.sdkOptionsImportPath ?? './sdk-options.js';\n const sdkClassName = input.sdkClassName ?? 'Sdk';\n\n const lines: string[] = [];\n lines.push(`import type { SdkOptions } from '${sdkOptionsImportPath}';`);\n lines.push(`import { createSdkFetch } from '${sdkOptionsImportPath}';`);\n\n const importedClients = new Set<string>();\n const pushClientImport = (c: SdkClientInfo): void => {\n const key = `${c.className}|${c.importPath}`;\n if (importedClients.has(key)) return;\n importedClients.add(key);\n lines.push(`import { ${c.className} } from '${c.importPath}';`);\n };\n // Areas first, then top-level — keeps the aggregator's import order stable.\n for (const area of input.areas) pushClientImport(area.client);\n for (const c of input.topLevelClients) pushClientImport(c);\n lines.push('');\n\n lines.push(`export class ${sdkClassName} {`);\n for (const area of input.areas) {\n lines.push(` readonly ${deriveAreaPropertyName(area.area)}: ${area.client.className};`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` readonly ${c.propertyName}: ${c.className};`);\n }\n lines.push('');\n lines.push(' constructor(options: SdkOptions) {');\n lines.push(' const sdkFetch = options.fetch ?? createSdkFetch(options);');\n for (const area of input.areas) {\n lines.push(` this.${deriveAreaPropertyName(area.area)} = new ${area.client.className}(sdkFetch);`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` this.${c.propertyName} = new ${c.className}(sdkFetch);`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n","import { relative, dirname } from 'node:path';\nimport type { ContractRootNode, ModelNode, FieldNode } from '@contractkit/core';\nimport { computeModelsWithOutput, collectExternalOutputRefs } from '@contractkit/core';\nimport type { ContractCodegenContext } from './codegen-contract.js';\nimport {\n collectExternalRefs,\n collectExternalInputRefs,\n computeModelsWithInput,\n topoSortModels,\n resolveImportPath,\n rootNeedsScalar,\n} from './codegen-contract.js';\nimport { renderTsType, renderInputTsType, renderOutputTsType, quoteKey, JSON_VALUE_TYPE_DECL } from './ts-render.js';\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Generate plain TypeScript interfaces/types from a contract AST.\n * Unlike `generateContract()` which produces Zod schemas, this emits\n * vanilla TypeScript `interface` and `type` declarations suitable\n * for SDK consumers that don't need runtime validation.\n */\nexport function generatePlainTypes(root: ContractRootNode, context?: ContractCodegenContext): string {\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = computeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input/Output refs needed for variant fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? collectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n // Type-only imports for external references\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n lines.push(`import type { ${ref} } from '${importPath}';`);\n }\n if (allExternalRefs.length > 0) lines.push('');\n\n if (rootNeedsScalar(root, 'json')) {\n if (context?.jsonValueImportPath) {\n lines.push(`import type { JsonValue } from '${context.jsonValueImportPath}';`);\n } else {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n lines.push('');\n }\n\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n for (const model of topoSortModels(root.models)) {\n lines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, allModelsWithOutput, modelMap));\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\nfunction generateModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithOutput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);\n }\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = model.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(model.name) ?? false);\n\n const lines = needsInputSplit ? generateVisibilityModel(model, outPath, modelsWithInput, modelMap) : generateSimpleModel(model, outPath, modelMap);\n\n if (modelsWithOutput?.has(model.name)) {\n lines.push('');\n lines.push(...generateOutputModel(model, modelsWithOutput));\n }\n return lines;\n}\n\n/** Recursively collect every field name defined on `bases` and their ancestors. Used to detect\n * fields that the child re-declares without an explicit `override` keyword — those still need an\n * `Omit<Base, …>` wrap, otherwise the child's narrower/incompatible declaration collides with the\n * inherited one. */\nfunction collectInheritedFieldNames(bases: string[], modelMap: Map<string, ModelNode>): Set<string> {\n const result = new Set<string>();\n const visit = (name: string): void => {\n const m = modelMap.get(name);\n if (!m || m.type) return;\n for (const f of m.fields) result.add(f.name);\n for (const b of m.bases ?? []) visit(b);\n };\n for (const b of bases) visit(b);\n return result;\n}\n\n/** Names of fields the child declaration overrides — explicit `override` plus any field whose\n * name shadows an inherited one. The latter catches single-base redeclarations that omit the\n * `override` keyword (e.g. narrowing `kind: BusinessRoleKind` → `kind: 'employee'`). */\nfunction computeOverrideNames(model: ModelNode, modelMap?: Map<string, ModelNode>): string[] {\n const inherited = modelMap ? collectInheritedFieldNames(model.bases ?? [], modelMap) : new Set<string>();\n return model.fields.filter(f => f.override || inherited.has(f.name)).map(f => f.name);\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n lines.push(` * ${model.description}`);\n }\n\n const relPath = outPath ? relative(dirname(outPath), model.loc.file) : model.loc.file;\n lines.push(` * generated from [${model.name}](file://./${relPath}#L${model.loc.line})`);\n lines.push(' */');\n return lines;\n}\n\nfunction generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export type ${model.name} = ${renderTsType(model.type!)};`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export type ${model.name}Input = ${renderInputTsType(model.type!, modelsWithInput)};`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = ${renderOutputTsType(model.type!, modelsWithOutput)};`);\n }\n return lines;\n}\n\n/** Build the `extends` clause for a model.\n * Each entry in `overrideNames` is wrapped in `Omit<Base, 'name1' | 'name2'>` per base so the\n * subclass can legally redeclare those fields with new (possibly incompatible) types.\n * TypeScript's `Omit<T, K extends keyof any>` tolerates omit keys that don't appear on the base,\n * so we apply the same omit list to every base without per-base field-set lookup. */\nfunction buildExtendsClause(bases: string[], overrideNames: string[], baseNameResolver: (b: string) => string): string {\n if (bases.length === 0) return '';\n if (overrideNames.length === 0) return ` extends ${bases.map(baseNameResolver).join(', ')}`;\n const omitKeys = overrideNames.map(n => `'${n}'`).join(' | ');\n const wrapped = bases.map(b => `Omit<${baseNameResolver(b)}, ${omitKeys}>`);\n return ` extends ${wrapped.join(', ')}`;\n}\n\nfunction generateSimpleModel(model: ModelNode, outPath?: string, modelMap?: Map<string, ModelNode>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n\n for (const field of model.fields) {\n lines.push(` ${renderField(field)}`);\n }\n\n lines.push('}');\n return lines;\n}\n\nfunction generateVisibilityModel(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelMap?: Map<string, ModelNode>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n\n // Read type — omit writeonly fields\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n for (const field of readFields) {\n lines.push(` ${renderField(field)}`);\n }\n lines.push('}');\n lines.push('');\n\n // Write type — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read type\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n const inputResolver = (b: string) => (modelsWithInput?.has(b) ? `${b}Input` : b);\n lines.push(`export interface ${model.name}Input${buildExtendsClause(bases, overrideNames, inputResolver)} {`);\n for (const field of writeFields) {\n lines.push(` ${modelsWithInput ? renderInputField(field, modelsWithInput) : renderField(field)}`);\n }\n lines.push('}');\n\n return lines;\n}\n\n// ─── Field rendering ──────────────────────────────────────────────────────\n\nfunction renderField(field: FieldNode): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderTsType(field.type);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n if (jsdocParts.length > 0) {\n return `/** ${jsdocParts.join(' ')} */\\n ${line}`;\n }\n return line;\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderInputTsType(field.type, modelsWithInput);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n if (jsdocParts.length > 0) {\n return `/** ${jsdocParts.join(' ')} */\\n ${line}`;\n }\n return line;\n}\n\n// ─── Output (post-transform wire shape) ──────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyOutputCase(name: string, c: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!c || c === 'camel') return name;\n if (c === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\n/**\n * Emit `${name}Output` for a model in the output transitive set.\n * - Direct hits (model.outputCase set): rename keys per the transform and substitute nested refs.\n * - Transitive hits: keep field names as-is but substitute nested refs with their Output variants.\n *\n * `extends` is dropped for direct-hit models because the Zod schema flattens fields when an\n * ancestor has format(...) (see `flattenFormatChain` in codegen-contract); we mirror that here\n * so the plain interface matches the wire shape produced by the Zod transform.\n */\nfunction generateOutputModel(model: ModelNode, modelsWithOutput: Set<string>): string[] {\n const lines: string[] = [];\n const outputCase = model.outputCase && model.outputCase !== 'camel' ? model.outputCase : undefined;\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n\n // Transitive-only (no direct outputCase): preserve `extends` and original key names.\n if (!outputCase) {\n const baseExt =\n model.bases?.[0] && modelsWithOutput.has(model.bases?.[0])\n ? ` extends ${model.bases?.[0]}Output`\n : model.bases?.[0]\n ? ` extends ${model.bases?.[0]}`\n : '';\n lines.push(`export interface ${model.name}Output${baseExt} {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, model.outputCase, modelsWithOutput)}`);\n }\n lines.push('}');\n return lines;\n }\n\n // Direct hit: emit a flat interface with renamed keys.\n lines.push(`export interface ${model.name}Output {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, outputCase, modelsWithOutput)}`);\n }\n lines.push('}');\n return lines;\n}\n\nfunction renderOutputField(field: FieldNode, outputCase: 'camel' | 'snake' | 'pascal' | undefined, modelsWithOutput: Set<string>): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n const key = applyOutputCase(field.name, outputCase);\n let typeStr = renderOutputTsType(field.type, modelsWithOutput);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(key)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n if (jsdocParts.length > 0) {\n return `/** ${jsdocParts.join(' ')} */\\n ${line}`;\n }\n return line;\n}\n","import { resolve, join, relative, dirname } from 'node:path';\nimport type { ContractRootNode, OpRootNode } from '@contractkit/core';\nimport { collectTypeRefs, collectPublicTypeNames } from '@contractkit/core';\n\nexport const TEMPLATE_VAR_RE = /\\{\\w+\\}/;\n\nexport function resolveTemplate(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{(\\w+)\\}/g, (_, key) => vars[key] ?? `{${key}}`);\n}\n\nexport function includesFilename(p: string): boolean {\n const last = p.split('/').pop() ?? '';\n return last.includes('.');\n}\n\nexport function commonDir(files: string[], rootDir: string): string {\n if (files.length === 0) return resolve(rootDir);\n const parts = files.map(f => dirname(f).split('/'));\n const first = parts[0]!;\n let depth = first.length;\n for (const p of parts) {\n for (let i = 0; i < depth; i++) {\n if (p[i] !== first[i]) {\n depth = i;\n break;\n }\n }\n }\n return first.slice(0, depth).join('/') || '/';\n}\n\n// ─── Server / Zod output paths ─────────────────────────────────────────────\n\nexport function computeOpOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n const baseName = filePath.split('/').pop()!;\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n const defaultName = `${filename}${defaultSuffix}`;\n const baseOutDir = resolve(baseDir);\n\n if (output && TEMPLATE_VAR_RE.test(output)) {\n const resolved = resolveTemplate(output, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return join(baseOutDir, resolved);\n return join(baseOutDir, resolved, defaultName);\n }\n if (output) {\n if (includesFilename(output)) return join(baseOutDir, output);\n return join(baseOutDir, output, relDir, defaultName);\n }\n return join(baseOutDir, relDir, defaultName);\n}\n\nexport function computeContractOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n return computeOpOutPath(filePath, baseDir, output, defaultSuffix, commonRoot, meta);\n}\n\n// ─── SDK output paths ──────────────────────────────────────────────────────\n\nexport function computeSdkOutPath(\n filePath: string,\n rootDir: string,\n clientOutput: string | undefined,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.client.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return join(baseOutDir, resolved);\n return join(baseOutDir, resolved, defaultOutName);\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return join(baseOutDir, clientOutput);\n return join(baseOutDir, clientOutput, relDir, defaultOutName);\n }\n return join(baseOutDir, relDir, defaultOutName);\n}\n\n/**\n * Resolve the output path for a synthesized `<area>.client.ts` — the file holding the\n * `<Area>Client` class that aggregates an area's inlined methods and subarea wiring.\n *\n * Uses the same `output.clients` template as leaf clients, with `{filename}` and `{area}`\n * substituted to the area name and `{subarea}` substituted to the empty string. Resulting\n * double-slashes from the empty substitution are collapsed, and a final segment that\n * would otherwise begin with a dot (e.g. `.client.ts` from `{subarea}.client.ts`) is\n * prefixed with the area so the file isn't hidden.\n */\nexport function computeSdkAreaClientOutPath(area: string, rootDir: string, clientOutput: string | undefined): string {\n const filename = area;\n const baseOutDir = resolve(rootDir);\n const fixHiddenSegment = (path: string): string => {\n const segments = path.split('/');\n const last = segments[segments.length - 1] ?? '';\n if (last.startsWith('.')) segments[segments.length - 1] = `${filename}${last}`;\n return segments.join('/');\n };\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: '', ext: 'ck', area, subarea: '' });\n const cleaned = fixHiddenSegment(resolved.replace(/\\/+/g, '/').replace(/^\\//, ''));\n if (includesFilename(cleaned)) return join(baseOutDir, cleaned);\n return join(baseOutDir, cleaned, `${filename}.client.ts`);\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return join(baseOutDir, clientOutput);\n return join(baseOutDir, clientOutput, `${filename}.client.ts`);\n }\n return join(baseOutDir, `${filename}.client.ts`);\n}\n\nexport function computeSdkTypeOutPath(\n filePath: string,\n rootDir: string,\n typeOutput: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (TEMPLATE_VAR_RE.test(typeOutput)) {\n const resolved = resolveTemplate(typeOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return join(baseOutDir, resolved);\n return join(baseOutDir, resolved, defaultOutName);\n }\n if (includesFilename(typeOutput)) return join(baseOutDir, typeOutput);\n return join(baseOutDir, typeOutput, relDir, defaultOutName);\n}\n\nexport function generateBarrelFiles(contractPaths: string[]): { outPath: string; content: string }[] {\n const byDir = new Map<string, string[]>();\n for (const outPath of contractPaths) {\n const dir = dirname(outPath);\n const group = byDir.get(dir) ?? [];\n group.push(outPath);\n byDir.set(dir, group);\n }\n const results: { outPath: string; content: string }[] = [];\n for (const [dir, files] of byDir) {\n const exports = files\n .map(f => `export * from './${f.split('/').pop()!.replace(/\\.ts$/, '.js')}';`)\n .sort()\n .join('\\n');\n results.push({ outPath: join(dir, 'index.ts'), content: `// Auto-generated barrel file\\n${exports}\\n` });\n }\n return results;\n}\n\nexport function computePubliclyReachableTypes(\n opAsts: OpRootNode[],\n contractAsts: ContractRootNode[],\n modelsWithInput: Set<string>,\n modelsWithOutput: Set<string> = new Set(),\n): Set<string> | null {\n if (opAsts.length === 0) return null;\n const reachable = new Set<string>();\n for (const opAst of opAsts) {\n for (const name of collectPublicTypeNames(opAst, modelsWithInput, modelsWithOutput)) reachable.add(name);\n }\n const modelDeps = new Map<string, Set<string>>();\n for (const contractAst of contractAsts) {\n for (const model of contractAst.models) {\n const deps = new Set<string>();\n if (model.bases) for (const b of model.bases) deps.add(b);\n if (model.type) collectTypeRefs(model.type, deps);\n for (const field of model.fields) collectTypeRefs(field.type, deps);\n modelDeps.set(model.name, deps);\n }\n }\n const frontier = [...reachable];\n while (frontier.length > 0) {\n const name = frontier.pop()!;\n const baseName = name.endsWith('Input') ? name.slice(0, -5) : name.endsWith('Output') ? name.slice(0, -6) : name;\n for (const dep of modelDeps.get(baseName) ?? []) {\n if (!reachable.has(dep)) {\n reachable.add(dep);\n frontier.push(dep);\n }\n if (modelsWithInput.has(dep)) {\n const inputDep = `${dep}Input`;\n if (!reachable.has(inputDep)) {\n reachable.add(inputDep);\n frontier.push(inputDep);\n }\n }\n if (modelsWithOutput.has(dep)) {\n const outputDep = `${dep}Output`;\n if (!reachable.has(outputDep)) {\n reachable.add(outputDep);\n frontier.push(outputDep);\n }\n }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BAAyBlB,0BAAAA;EACpC;AACJ;AAPSiB;AAUT,SAASuB,cAAc5B,cAAsB6B,UAA6B;AACtE,MAAI;AACA6L,cAAU1F,SAAQhI,YAAAA,GAAe;MAAE2N,WAAW;IAAK,CAAA;AACnDC,kBAAc5N,cAAc6N,6BAA6BhM,QAAAA,GAAW,OAAA;EACxE,QAAQ;EAER;AACJ;AAPSD;AAST,SAASN,iBAAiBwM,UAAkB;AACxC,MAAIA,SAASrD,WAAW,EAAG;AAC3B,QAAMsD,cAAc,oBAAIzH,IAAAA;AACxB,aAAW0H,OAAOF,UAAU;AACxB,QAAIzM,WAAW2M,GAAAA,GAAM;AACjBC,aAAOD,KAAK;QAAEE,OAAO;MAAK,CAAA;AAC1BH,kBAAYvB,IAAIxE,SAAQgG,GAAAA,CAAAA;IAC5B;EACJ;AAEA,aAAWG,OAAOJ,aAAa;AAC3B,QAAIK,UAAUD;AACd,WAAOC,QAAQ3D,SAAS,GAAG;AACvB,UAAI;AACA,YAAI4D,YAAYD,OAAAA,EAAS3D,WAAW,GAAG;AACnC6D,oBAAUF,OAAAA;AACVA,oBAAUpG,SAAQoG,OAAAA;QACtB,OAAO;AACH;QACJ;MACJ,QAAQ;AACJ;MACJ;IACJ;EACJ;AACJ;AAzBS9M;AA4BT,SAASwE,gBAAgBnG,QAAe;AACpC,SAAO4O,KAAKC,UAAU7O,UAAU,IAAA;AACpC;AAFSmG;","names":["resolve","join","relative","dirname","basename","existsSync","readFileSync","writeFileSync","mkdirSync","rmSync","readdirSync","rmdirSync","relative","dirname","collectTypeRefs","computeModelsWithOutput","ckComputeModelsWithOutput","collectExternalOutputRefs","ckCollectExternalOutputRefs","modeToWrapper","mode","computeModelsWithInput","models","externalModelsWithInput","Set","result","model","fields","some","f","visibility","add","name","changed","has","refs","field","collectTypeRefs","type","bases","b","ref","generateComments","outPath","lines","push","deprecated","description","relPath","relative","dirname","loc","file","line","generateContract","root","context","needsDateTime","rootNeedsDateTime","needsDuration","rootNeedsScalar","needsInterval","needsBinary","needsDatetime","needsJson","externalRefs","collectExternalRefs","modelsWithInput","localModelsWithInput","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","ckComputeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","ckCollectExternalOutputRefs","allExternalRefs","sort","luxonImports","length","join","importPath","resolveImportPath","modelsWithWriteonly","filter","m","map","modelMap","Map","topoSortModels","generateModel","currentOutPath","flattenFormatChain","firstBase","parent","get","flatParent","parentHasFormat","inputCase","undefined","outputCase","merged","set","values","generateTypeAlias","effective","needsInputSplit","generateThreeSchemaModel","generateSimpleModel","renderType","renderInputType","wrapper","hasInputTransform","hasOutputTransform","inputBody","renderFieldsAsSnakeCase","renderFieldsAsPascalCase","renderFields","l","inputKey","applyCase","outputKey","quoteKey","typeSource","body","head","tail","slice","buildExtendChain","resolveName","collectEffectiveWritableFieldNames","modelName","base","delete","allFields","hasWriteonly","baseBody","readFields","readBody","writeFields","writeBody","renderInputFields","fieldsToOmit","omitClause","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","caseTransform","defaultMode","flatMap","renderField","pascalKey","expr","default","nullable","dv","escapeString","String","optional","snakeKey","parseCaseTransform","kind","renderScalar","renderArray","renderTuple","renderRecord","renderEnum","renderLiteral","renderUnion","renderDiscriminatedUnion","renderIntersection","inner","renderInlineObject","renderRegexLiteral","source","regexHasAnchor","startsWith","endsWith","i","backslashes","e","min","max","len","regex","fmt","format","validParts","validation","message","a","item","t","items","r","key","value","vals","v","u","members","discriminator","first","rest","every","member","fieldLines","o","snakeLines","joined","transformEntries","val","pascalLines","renderInputScalar","renderInputField","renderQueryType","renderQueryField","isValidIdentifier","test","typeNeedsDateTime","typeNeedsScalar","localNames","collectInputTypeRefs","out","forEach","deps","localDeps","inDegree","d","dep","remaining","queue","sorted","shift","other","rem","includes","refName","refOutPath","modelOutPaths","fromDir","rel","moduleName","pascalToDotCase","resolveModifiers","resolveSecurity","SECURITY_NONE","classifyContentType","JSON_VALUE_TYPE_DECL","quoteKey","name","test","headerNameToProperty","parts","split","filter","Boolean","map","p","i","lower","toLowerCase","charAt","toUpperCase","slice","join","renderTsType","type","kind","renderTsScalar","inner","item","needsParens","items","key","value","values","v","String","members","renderTsInlineObject","fields","entries","f","opt","optional","renderInputTsType","modelsWithInput","size","has","m","renderOutputTsType","modelsWithOutput","basename","dirname","relative","bodyParserToken","contentType","classifyContentType","bodyTypesStructurallyEqual","a","b","kind","bb","name","min","max","len","regex","format","item","items","length","every","x","i","key","value","values","v","members","m","discriminator","lazy","inner","mode","fields","f","g","optional","nullable","visibility","default","deprecated","type","generateOp","root","options","types","collectTypes","modelsWithInput","modelsWithOutput","services","collectServices","routerName","deriveRouterName","file","needsParseAndValidate","routeNeedsValidation","body","needsSignature","fileNeedsSignature","needsSecurity","fileNeedsSecurity","koaImports","push","join","svc","modulePath","meta","deriveModulePath","servicePathTemplate","generateTypeImports","opNeedsDateTime","helpers","opNeedsScalar","lines","relFile","outPath","relative","dirname","basename","includeInternal","route","routes","op","operations","resolveModifiers","includes","generateHandler","allContent","needsZod","test","desc","description","loc","line","effectiveSecurity","resolveSecurity","SECURITY_NONE","mods","method","path","replace","bodies","request","hasBody","isSingleMultipart","middlewares","args","requireMfa","undefined","parserTokens","Array","from","Set","map","tokensExpr","t","signature","middlewareStr","generateParamValidation","params","paramsMode","query","queryMode","headers","headersMode","renderInputType","bodyType","annotation","primaryResponse","responses","find","r","serviceParts","inferService","respHeaders","hasRespHeaders","headersAnnotation","h","quoteKey","headerNameToProperty","renderOutputTsType","prelude","formatTypeAnnotation","className","methodName","buildArgs","statusCode","accessor","JSON","stringify","service","cls","split","baseName","deriveBaseName","inferMethodName","hasParam","nodes","p","has","schema","renderType","source","ctxExpr","varName","suffix","isQuery","typeName","lhs","modeToWrapper","param","isValidIdentifier","renderQueryType","node","opFile","modelOutPaths","byFile","Map","unresolved","typeOutPath","get","group","set","fromDir","names","rel","startsWith","sort","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","resp","collectOutputTypeNodeRefs","out","add","forEach","paramSourceNeedsDateTime","some","typeNeedsDateTime","paramSourceNeedsScalar","typeNeedsScalar","inferredService","hasParamSource","base","pop","s","charAt","toUpperCase","slice","serviceName","template","kebab","toLowerCase","module","runIncrementalCodegen","parseIncrementalManifest","emptyIncrementalManifest","serializeIncrementalManifest","hashFingerprint","collectTransitiveModelRefs","resolveModifiers","isJsonMime","classifyContentType","basename","dirname","relative","jsonOrFormSerialize","varName","contentType","renderSerializeExpr","bodies","ctVar","arms","slice","last","length","expr","i","arm","classifyBodyStrategy","op","request","kind","body","every","b","bodyTypesStructurallyEqual","bodyType","some","hasPublicOperations","root","includeInternal","route","routes","operations","resolveModifiers","includes","generateSdk","options","lines","types","collectTypes","modelsWithInput","modelsWithOutput","clientClassName","deriveClientClassName","file","push","generateTypeImports","sdkOptionsPath","outPath","rel","relative","dirname","replace","startsWith","jsonImport","sdkNeedsJson","valueImports","sdkNeedsBigIntReplacer","sdkNeedsBigIntReviver","sdkNeedsQueryString","join","JSON_VALUE_TYPE_DECL","relFile","basename","mods","generateMethod","generateClientMethods","methodNames","deriveMethodName","methodName","httpMethod","method","toUpperCase","params","buildMethodParams","paramStr","map","p","name","optional","type","primaryResponse","responses","find","r","isVoid","respCategory","classifyContentType","dataType","renderOutputTsType","respHeaders","headers","hasRespHeaders","headersShape","h","quoteKey","headerNameToProperty","returnType","desc","description","tags","tag","urlExpr","buildUrlExpression","path","hasQuery","query","fetchUrl","strategy","hasBody","hasOpHeaders","defaultCt","nonMultipart","fetchArgs","cat","lastHeaderIdx","findIndex","a","existing","inner","resultPrefix","split","readBodyExpr","headerEntries","_","_match","nodes","renderInputTsType","typeName","has","node","ctUnion","fields","sdk","nameToMethodName","inferMethodName","parts","filter","Boolean","charAt","toLowerCase","segments","s","seg","paramName","segParts","sp","deriveBaseName","base","pop","deriveClientPropertyName","getAreaSubarea","area","meta","subarea","pascal","value","camel","deriveAreaClientClassName","deriveAreaPropertyName","deriveSubareaClientClassName","deriveSubareaPropertyName","Set","publicOps","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","resp","collectOutputTypeNodeRefs","sort","out","add","item","members","forEach","m","f","source","param","test","isJsonMime","check","src","typeNeedsScalar","items","t","key","opFile","modelOutPaths","byFile","Map","unresolved","typeOutPath","get","group","set","fromDir","names","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","template","module","generateSdkOptions","generateAreaClient","input","inlineFiles","subareaClients","className","collectedMethodLines","seenMethods","typesByImportPath","unresolvedTypes","needsJson","needsBigIntReplacer","needsBigIntReviver","needsQueryString","inline","codegenOptions","methodLines","Error","typesForFile","sdkOptionsRel","keys","importedClients","sc","client","importPath","propertyName","fetchModifier","ln","generateSdkAggregator","sdkOptionsImportPath","sdkClassName","pushClientImport","c","areas","topLevelClients","relative","dirname","computeModelsWithOutput","collectExternalOutputRefs","generatePlainTypes","root","context","externalRefs","collectExternalRefs","lines","externalModelsWithInput","modelsWithInput","Set","localModelsWithInput","computeModelsWithInput","models","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","computeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","collectExternalOutputRefs","allExternalRefs","sort","ref","importPath","resolveImportPath","push","length","rootNeedsScalar","jsonValueImportPath","JSON_VALUE_TYPE_DECL","modelMap","Map","map","m","name","model","topoSortModels","generateModel","currentOutPath","join","outPath","type","generateTypeAlias","needsInputSplit","fields","some","f","visibility","has","generateVisibilityModel","generateSimpleModel","generateOutputModel","collectInheritedFieldNames","bases","result","visit","get","add","b","computeOverrideNames","inherited","filter","override","generateComments","deprecated","description","relPath","relative","dirname","loc","file","line","renderTsType","renderInputTsType","renderOutputTsType","buildExtendsClause","overrideNames","baseNameResolver","omitKeys","n","wrapped","field","renderField","readFields","writeFields","inputResolver","renderInputField","opt","optional","default","undefined","typeStr","nullable","quoteKey","jsdocParts","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","slice","applyOutputCase","outputCase","baseExt","renderOutputField","key","resolve","join","relative","dirname","collectTypeRefs","collectPublicTypeNames","TEMPLATE_VAR_RE","resolveTemplate","template","vars","replace","_","key","includesFilename","p","last","split","pop","includes","commonDir","files","rootDir","length","resolve","parts","map","f","dirname","first","depth","i","slice","join","computeOpOutPath","filePath","baseDir","output","defaultSuffix","commonRoot","meta","baseName","relDir","relative","filename","defaultName","baseOutDir","test","resolved","dir","ext","computeContractOutPath","computeSdkOutPath","clientOutput","endsWith","defaultOutName","computeSdkAreaClientOutPath","area","fixHiddenSegment","path","segments","startsWith","subarea","cleaned","computeSdkTypeOutPath","typeOutput","generateBarrelFiles","contractPaths","byDir","Map","outPath","group","get","push","set","results","exports","sort","content","computePubliclyReachableTypes","opAsts","contractAsts","modelsWithInput","modelsWithOutput","Set","reachable","opAst","name","collectPublicTypeNames","add","modelDeps","contractAst","model","models","deps","bases","b","type","collectTypeRefs","field","fields","frontier","dep","has","inputDep","outputDep","TYPESCRIPT_CODEGEN_VERSION","CACHE_MANIFEST_FILENAME","plugin","name","generateTargets","inputs","ctx","config","options","runTypescriptCodegen","rootDir","createTypescriptPlugin","manifestPath","resolve","cacheDir","prevManifest","cacheEnabled","readManifest","emptyIncrementalManifest","units","globalFiles","server","collectServerOutput","sdk","collectSdkOutput","zod","collectZodOutput","types","collectTypesOutput","result","runIncrementalCodegen","codegenVersion","fileExists","existsSync","deleteStalePaths","deletedPaths","relativePath","content","filesToWrite","emitFile","writeManifest","manifest","buildModelMap","contractRoots","map","Map","root","model","models","set","collectContractRootRefs","modelMap","seeds","m","type","push","f","fields","bases","b","kind","collectTransitiveModelRefs","collectOpRootRefs","route","routes","params","paramSourceTypes","op","operations","query","headers","request","body","bodies","bodyType","resp","responses","h","src","out","n","nodes","node","sliceOutPathMap","refs","modelOutPaths","modelsWithInput","modelsWithOutput","slice","ref","sort","p","get","has","ip","sliceModelSet","ownNames","serverBase","baseDir","allFiles","r","file","opRoots","commonRoot","commonDir","subConfigKey","stableSubConfig","serverModelOutPaths","typeEntries","output","ast","typeOutPath","computeContractOutPath","meta","Set","fingerprint","hashFingerprint","v","outPath","outPathSlice","sub","key","render","renderCtx","currentOutPath","generateContract","generatePlainTypes","computeOpOutPath","servicePathTemplate","includeInternal","generateOp","sdkBase","sdkName","sdkOutput","sdkEntryPath","join","TEMPLATE_VAR_RE","test","resolveTemplate","sdkOptionsPath","dirname","ckCommonRoot","sdkModelOutPaths","sdkTypePaths","sdkClientInfos","sdkContractEntries","publicTypes","computePubliclyReachableTypes","computeSdkTypeOutPath","some","rel","relative","replace","startsWith","jsonValueImportPath","areaBuckets","topLevelEntries","clients","sdkOutPath","computeSdkOutPath","hasPublicOperations","area","subarea","getAreaSubarea","bucket","leaves","inlineRoots","entries","leaf","className","deriveSubareaClientClassName","propertyName","deriveSubareaPropertyName","generateSdk","typeImportPathTemplate","undefined","clientClassName","deriveClientClassName","deriveClientPropertyName","generateSdkOptions","hasAnything","length","size","areaClientOutPaths","sdkEntryDir","sdkOptionsRel","sdkOptionsImportPath","sdkClassName","split","s","charAt","toUpperCase","toClientImport","sourceDir","info","importPath","topLevelClients","e","areaInfos","sortedAreas","a","localeCompare","areaClientOutPath","computeSdkAreaClientOutPath","areaClassName","deriveAreaClientClassName","areaPropertyName","deriveAreaPropertyName","subareaClients","l","client","allInlineRefs","add","inlineFilesForGen","codegenOptions","generateAreaClient","inlineFiles","generateSdkAggregator","areas","sdkSrcDir","sdkTypeBarrels","generateBarrelFiles","barrel","rootExports","basename","c","zodBase","typesBase","parseIncrementalManifest","readFileSync","mkdirSync","recursive","writeFileSync","serializeIncrementalManifest","absPaths","removedDirs","abs","rmSync","force","dir","current","readdirSync","rmdirSync","JSON","stringify"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/codegen-contract.ts","../src/codegen-operation.ts","../src/ts-render.ts","../src/codegen-sdk.ts","../src/codegen-plain-types.ts","../src/path-utils.ts"],"sourcesContent":["import { resolve, join, relative, dirname, basename } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, rmdirSync } from 'node:fs';\nimport { generateContract } from './codegen-contract.js';\nimport { generateOp } from './codegen-operation.js';\nimport type {\n ContractKitPlugin,\n PluginContext,\n ContractRootNode,\n OpRootNode,\n ModelNode,\n IncrementalManifest,\n IncrementalUnit,\n IncrementalOutputFile,\n} from '@contractkit/core';\nimport {\n runIncrementalCodegen,\n parseIncrementalManifest,\n emptyIncrementalManifest,\n serializeIncrementalManifest,\n hashFingerprint,\n collectTransitiveModelRefs,\n collectTypeRefs,\n} from '@contractkit/core';\nimport {\n generateSdk,\n generateSdkOptions,\n generateSdkAggregator,\n generateAreaClient,\n deriveClientClassName,\n deriveClientPropertyName,\n deriveAreaClientClassName,\n deriveAreaPropertyName,\n deriveSubareaClientClassName,\n deriveSubareaPropertyName,\n getAreaSubarea,\n hasPublicOperations,\n type SdkClientInfo,\n type SdkAreaInfo,\n} from './codegen-sdk.js';\nimport { generatePlainTypes } from './codegen-plain-types.js';\nimport {\n TEMPLATE_VAR_RE,\n resolveTemplate,\n commonDir,\n computeOpOutPath,\n computeContractOutPath,\n computeSdkOutPath,\n computeSdkAreaClientOutPath,\n computeSdkTypeOutPath,\n generateBarrelFiles,\n computePubliclyReachableTypes,\n} from './path-utils.js';\n\n// ─── Sub-config interfaces ─────────────────────────────────────────────────\n\nexport interface ServerConfig {\n /** Directory (relative to rootDir) where server files are written. Default: rootDir. */\n baseDir?: string;\n /** When true, `output.types` emits Zod schema files (via `generateContract`). When false/omitted, emits plain TypeScript. */\n zod?: boolean;\n output?: {\n /** Path template for Koa router files. Supports {filename}, {dir}, {area}. */\n routes?: string;\n /** Path template for type/schema files. Supports {filename}, {dir}, {area}. */\n types?: string;\n };\n /** Import path template for service implementations. */\n servicePathTemplate?: string;\n /** Whether to emit handlers for `internal` operations. Default true. */\n includeInternal?: boolean;\n}\n\nexport interface SdkConfig {\n baseDir?: string;\n name?: string;\n zod?: boolean;\n output?: {\n sdk?: string;\n types?: string;\n clients?: string;\n };\n includeInternal?: boolean;\n}\n\nexport interface ZodConfig {\n baseDir?: string;\n output?: string;\n}\n\nexport interface TypesConfig {\n baseDir?: string;\n output?: string;\n}\n\nexport interface TypescriptPluginConfig {\n server?: ServerConfig;\n sdk?: SdkConfig;\n zod?: ZodConfig;\n types?: TypesConfig;\n}\n\n// ─── Caching constants ─────────────────────────────────────────────────────\n\n/** Bumped when the codegen output shape changes in a way that should bust every per-file fingerprint. */\nexport const TYPESCRIPT_CODEGEN_VERSION = '1';\n\n/** Filename for the persisted TypeScript manifest under the CLI cache directory. */\nconst CACHE_MANIFEST_FILENAME = 'typescript-manifest.json';\n\n// ─── Plugin entry points ──────────────────────────────────────────────────\n\nconst plugin: ContractKitPlugin = {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n const config = ctx.options as TypescriptPluginConfig;\n await runTypescriptCodegen(inputs, ctx, config, ctx.rootDir);\n },\n};\n\nexport default plugin;\n\n/** Build a `@contractkit/plugin-typescript` instance with explicit configuration, for programmatic use. */\nexport function createTypescriptPlugin(config: TypescriptPluginConfig, rootDir: string): ContractKitPlugin {\n return {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n await runTypescriptCodegen(inputs, ctx, config, rootDir);\n },\n };\n}\n\n/**\n * Shared orchestration. Each sub-generator (server / sdk / zod / types) contributes a\n * set of cacheable units (per-file fingerprints) plus a set of always-regenerated global\n * files (aggregators, barrels, sdk-options). Units share a single manifest so the cache\n * survives cross-cutting reads — the manifest lives at `<rootDir>/.contractkit-typescript-manifest.json`.\n *\n * Honors `ctx.cacheEnabled` — `--force` bypasses the manifest entirely.\n */\nasync function runTypescriptCodegen(\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n ctx: PluginContext,\n config: TypescriptPluginConfig,\n rootDir: string,\n): Promise<void> {\n const manifestPath = resolve(ctx.cacheDir, CACHE_MANIFEST_FILENAME);\n const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n\n const units: IncrementalUnit[] = [];\n const globalFiles: IncrementalOutputFile[] = [];\n\n if (config.server) collectServerOutput(config.server, rootDir, inputs, units);\n if (config.sdk) collectSdkOutput(config.sdk, rootDir, inputs, units, globalFiles);\n if (config.zod) collectZodOutput(config.zod, rootDir, inputs, units);\n if (config.types) collectTypesOutput(config.types, rootDir, inputs, units);\n\n const result = runIncrementalCodegen({\n codegenVersion: TYPESCRIPT_CODEGEN_VERSION,\n prevManifest,\n globalFiles,\n units,\n // Paths are absolute, so existsSync works directly.\n fileExists: existsSync,\n });\n\n deleteStalePaths(result.deletedPaths);\n\n for (const { relativePath, content } of result.filesToWrite) {\n ctx.emitFile(relativePath, content);\n }\n\n writeManifest(manifestPath, result.manifest);\n}\n\n// ─── Cross-file dependency analysis ────────────────────────────────────────\n\n/** Build a quick lookup from model name → its definition. */\nfunction buildModelMap(contractRoots: readonly ContractRootNode[]): Map<string, ModelNode> {\n const map = new Map<string, ModelNode>();\n for (const root of contractRoots) {\n for (const model of root.models) map.set(model.name, model);\n }\n return map;\n}\n\n/** Collect every model referenced by this contract root (own models' fields + bases). Used to slice cross-file fingerprint inputs to just what this file actually depends on. */\nfunction collectContractRootRefs(root: ContractRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const m of root.models) {\n if (m.type) seeds.push(m.type);\n for (const f of m.fields) seeds.push(f.type);\n if (m.bases) {\n for (const b of m.bases) seeds.push({ kind: 'ref', name: b } as Parameters<typeof collectTypeRefs>[0]);\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\n/** Collect every model referenced by an op root's routes/operations (transitive). */\nfunction collectOpRootRefs(root: OpRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const route of root.routes) {\n if (route.params) seeds.push(...paramSourceTypes(route.params));\n for (const op of route.operations) {\n if (op.query) seeds.push(...paramSourceTypes(op.query));\n if (op.headers) seeds.push(...paramSourceTypes(op.headers));\n if (op.request) {\n for (const body of op.request.bodies) seeds.push(body.bodyType);\n }\n for (const resp of op.responses) {\n if (resp.bodyType) seeds.push(resp.bodyType);\n if (resp.headers) {\n for (const h of resp.headers) seeds.push(h.type);\n }\n }\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\nfunction paramSourceTypes(src: NonNullable<OpRootNode['routes'][number]['params']>): Parameters<typeof collectTypeRefs>[0][] {\n const out: Parameters<typeof collectTypeRefs>[0][] = [];\n if (src.kind === 'params') {\n for (const n of src.nodes) out.push(n.type);\n } else if (src.kind === 'ref') {\n out.push({ kind: 'ref', name: src.name } as Parameters<typeof collectTypeRefs>[0]);\n } else if (src.kind === 'type') {\n out.push(src.node);\n }\n return out;\n}\n\n/** Build a sorted, JSON-stable record of (modelName -> outPath) for refs this unit depends on. */\nfunction sliceOutPathMap(refs: Set<string>, modelOutPaths: Map<string, string>, modelsWithInput: Set<string>, modelsWithOutput: Set<string>): Record<string, string> {\n const slice: Record<string, string> = {};\n for (const ref of [...refs].sort()) {\n const p = modelOutPaths.get(ref);\n if (p) slice[ref] = p;\n if (modelsWithInput.has(ref)) {\n const ip = modelOutPaths.get(`${ref}Input`);\n if (ip) slice[`${ref}Input`] = ip;\n }\n if (modelsWithOutput.has(ref)) {\n const op = modelOutPaths.get(`${ref}Output`);\n if (op) slice[`${ref}Output`] = op;\n }\n }\n return slice;\n}\n\n/** Slice modelsWithInput/Output to only the names relevant to this unit. */\nfunction sliceModelSet(refs: Set<string>, ownNames: Set<string>, set: Set<string>): string[] {\n const result: string[] = [];\n for (const name of set) {\n if (refs.has(name) || ownNames.has(name)) result.push(name);\n }\n return result.sort();\n}\n\n// ─── Server sub-generator ──────────────────────────────────────────────────\n\nfunction collectServerOutput(\n config: ServerConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const serverBase = resolve(rootDir, config.baseDir ?? '.');\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const subConfigKey = stableSubConfig(config);\n\n // Pre-pass: register all model → outPath. Cross-file refs need to resolve correctly,\n // which means we need the COMPLETE map (not a slice) — even though each unit's fingerprint\n // only includes its own slice.\n const serverModelOutPaths = new Map<string, string>();\n const typeEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeContractOutPath(ast.file, serverBase, config.output.types, '.ts', commonRoot, ast.meta);\n typeEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n serverModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) serverModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) serverModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── Per-contract-root types unit ──\n for (const { ast, typeOutPath } of typeEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'server-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `server-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n const renderCtx = {\n modelOutPaths: serverModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n };\n const content = config.zod ? generateContract(ast, renderCtx) : generatePlainTypes(ast, renderCtx);\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Per-op-root router unit ──\n for (const ast of inputs.opRoots) {\n const outPath = computeOpOutPath(ast.file, serverBase, config.output?.routes, '.router.ts', commonRoot, ast.meta);\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'server-router',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n // The router imports types from each contract root's type file; the slice covers exactly that.\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n servicePathTemplate: config.servicePathTemplate ?? null,\n includeInternal: config.includeInternal ?? true,\n sub: subConfigKey,\n });\n units.push({\n key: `server-router::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateOp(ast, {\n servicePathTemplate: config.servicePathTemplate,\n outPath,\n modelOutPaths: serverModelOutPaths,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n }),\n },\n ],\n });\n }\n}\n\n// ─── SDK sub-generator ─────────────────────────────────────────────────────\n\nfunction collectSdkOutput(\n config: SdkConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n globalFiles: IncrementalOutputFile[],\n): void {\n const sdkBase = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;\n const sdkName = config.name;\n const sdkOutput = config.output?.sdk;\n const sdkEntryPath = sdkOutput\n ? join(sdkBase, TEMPLATE_VAR_RE.test(sdkOutput) ? resolveTemplate(sdkOutput, { name: sdkName ?? 'sdk' }) : sdkOutput)\n : join(sdkBase, 'sdk.ts');\n const sdkOptionsPath = join(dirname(sdkEntryPath), 'sdk-options.ts');\n const subConfigKey = stableSubConfig(config);\n\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const ckCommonRoot = commonDir(allFiles, rootDir);\n\n const sdkModelOutPaths = new Map<string, string>();\n const sdkTypePaths: string[] = [];\n const sdkClientInfos: { outPath: string; className: string; propertyName: string }[] = [];\n\n // ── Pre-pass: SDK type files ──\n const sdkContractEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n const publicTypes = computePubliclyReachableTypes(inputs.opRoots, inputs.contractRoots, modelsWithInput, modelsWithOutput);\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeSdkTypeOutPath(ast.file, sdkBase, config.output.types, ckCommonRoot, ast.meta);\n if (!typeOutPath) continue;\n if (publicTypes !== null && !ast.models.some(m => publicTypes.has(m.name))) continue;\n sdkTypePaths.push(typeOutPath);\n sdkContractEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n sdkModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) sdkModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) sdkModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── SDK type units ──\n for (const { ast, typeOutPath } of sdkContractEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'sdk-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sdkOptionsPath,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n let content: string;\n if (config.zod) {\n content = generateContract(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n });\n } else {\n let rel = relative(dirname(typeOutPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n content = generatePlainTypes(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n jsonValueImportPath: rel,\n });\n }\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Bucket op roots by area/subarea ──\n interface AreaBucket {\n leaves: { ast: OpRootNode; outPath: string; subarea: string }[];\n inlineRoots: OpRootNode[];\n }\n const areaBuckets = new Map<string, AreaBucket>();\n const topLevelEntries: { ast: OpRootNode; outPath: string }[] = [];\n\n if (config.output?.clients) {\n for (const ast of inputs.opRoots) {\n const sdkOutPath = computeSdkOutPath(ast.file, sdkBase, config.output.clients, ckCommonRoot, ast.meta);\n if (!sdkOutPath || !hasPublicOperations(ast, config.includeInternal)) continue;\n const { area, subarea } = getAreaSubarea(ast);\n if (area && subarea) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.leaves.push({ ast, outPath: sdkOutPath, subarea });\n areaBuckets.set(area, bucket);\n } else if (area) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.inlineRoots.push(ast);\n areaBuckets.set(area, bucket);\n } else {\n topLevelEntries.push({ ast, outPath: sdkOutPath });\n }\n }\n\n // ── Per-leaf-client (area+subarea) units ──\n for (const [area, bucket] of areaBuckets.entries()) {\n for (const leaf of bucket.leaves) {\n const className = deriveSubareaClientClassName(area, leaf.subarea);\n sdkClientInfos.push({ outPath: leaf.outPath, className, propertyName: deriveSubareaPropertyName(leaf.subarea) });\n const refs = collectOpRootRefs(leaf.ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-leaf-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: leaf.outPath,\n root: leaf.ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n sdkOptionsPath,\n className,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-leaf-client::${leaf.outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: leaf.outPath,\n content: generateSdk(leaf.ast, {\n typeImportPathTemplate: undefined,\n outPath: leaf.outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n clientClassName: className,\n }),\n },\n ],\n });\n }\n }\n\n // ── Top-level (no area) client units ──\n for (const { ast, outPath } of topLevelEntries) {\n const className = deriveClientClassName(ast.file);\n sdkClientInfos.push({ outPath, className, propertyName: deriveClientPropertyName(ast.file) });\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-top-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-top-client::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateSdk(ast, {\n typeImportPathTemplate: undefined,\n outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n }),\n },\n ],\n });\n }\n }\n\n // ── Global files: sdk-options, aggregator, barrels, root index ──\n // sdk-options.ts is a constant; the aggregator is small (just imports + a wrapper class)\n // and depends on the cross-cutting client list, so it's cheap to regenerate every run.\n // Per-area `<area>.client.ts` files are cached as their own units below.\n globalFiles.push({ relativePath: sdkOptionsPath, content: generateSdkOptions() });\n\n const hasAnything = sdkClientInfos.length > 0 || areaBuckets.size > 0;\n const areaClientOutPaths = new Map<string, string>(); // area → absolute outPath of <area>.client.ts\n if (hasAnything) {\n const sdkEntryDir = dirname(sdkEntryPath);\n const sdkOptionsRel = relative(sdkEntryDir, sdkOptionsPath).replace(/\\.ts$/, '.js');\n const sdkOptionsImportPath = sdkOptionsRel.startsWith('.') ? sdkOptionsRel : './' + sdkOptionsRel;\n const sdkClassName = sdkName\n ? sdkName\n .split(/[-._\\s]+/)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('') + 'Sdk'\n : 'Sdk';\n\n const toClientImport = (sourceDir: string, info: { outPath: string; className: string; propertyName: string }): SdkClientInfo => {\n let rel = relative(sourceDir, info.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n return { className: info.className, propertyName: info.propertyName, importPath: rel };\n };\n\n const topLevelClients: SdkClientInfo[] = topLevelEntries.map(e =>\n toClientImport(sdkEntryDir, {\n outPath: e.outPath,\n className: deriveClientClassName(e.ast.file),\n propertyName: deriveClientPropertyName(e.ast.file),\n }),\n );\n\n // ── Per-area `<area>.client.ts` units ──\n const areaInfos: SdkAreaInfo[] = [];\n const sortedAreas = [...areaBuckets.entries()].sort(([a], [b]) => a.localeCompare(b));\n for (const [area, bucket] of sortedAreas) {\n const areaClientOutPath = computeSdkAreaClientOutPath(area, sdkBase, config.output!.clients);\n areaClientOutPaths.set(area, areaClientOutPath);\n const areaClassName = deriveAreaClientClassName(area);\n const areaPropertyName = deriveAreaPropertyName(area);\n sdkClientInfos.push({ outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName });\n\n const subareaClients = bucket.leaves\n .sort((a, b) => a.subarea.localeCompare(b.subarea))\n .map(l => ({\n propertyName: deriveSubareaPropertyName(l.subarea),\n client: toClientImport(dirname(areaClientOutPath), {\n outPath: l.outPath,\n className: deriveSubareaClientClassName(area, l.subarea),\n propertyName: deriveSubareaPropertyName(l.subarea),\n }),\n }));\n\n // Fingerprint covers every input the area client depends on:\n // - all inline roots (full AST)\n // - subarea client metadata (className / propertyName / import path)\n // - the modelOutPaths slice for refs across all inline roots\n // - modelsWithInput/Output slices\n const allInlineRefs = new Set<string>();\n for (const r of bucket.inlineRoots) {\n for (const ref of collectOpRootRefs(r, modelMap)) allInlineRefs.add(ref);\n }\n const fingerprint = hashFingerprint({\n kind: 'sdk-area-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: areaClientOutPath,\n area,\n inlineRoots: bucket.inlineRoots,\n subareaClients,\n outPathSlice: sliceOutPathMap(allInlineRefs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(allInlineRefs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(allInlineRefs, new Set(), modelsWithOutput),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n\n const inlineFilesForGen = bucket.inlineRoots.map(root => ({\n root,\n codegenOptions: {\n typeImportPathTemplate: undefined,\n outPath: areaClientOutPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n includeInternal: config.includeInternal,\n },\n }));\n\n units.push({\n key: `sdk-area-client::${areaClientOutPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: areaClientOutPath,\n content: generateAreaClient({\n area,\n outPath: areaClientOutPath,\n inlineFiles: inlineFilesForGen,\n subareaClients,\n sdkOptionsPath,\n }),\n },\n ],\n });\n\n areaInfos.push({\n area,\n client: toClientImport(sdkEntryDir, { outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName }),\n });\n }\n\n globalFiles.push({\n relativePath: sdkEntryPath,\n content: generateSdkAggregator({ topLevelClients, areas: areaInfos, sdkOptionsImportPath, sdkClassName }),\n });\n }\n\n const sdkSrcDir = dirname(sdkEntryPath);\n const sdkTypeBarrels = generateBarrelFiles(sdkTypePaths);\n for (const barrel of sdkTypeBarrels) globalFiles.push({ relativePath: barrel.outPath, content: barrel.content });\n\n const rootExports: string[] = [`export * from './${basename(sdkOptionsPath).replace(/\\.ts$/, '.js')}';`];\n if (hasAnything) rootExports.push(`export * from './${basename(sdkEntryPath).replace(/\\.ts$/, '.js')}';`);\n for (const c of sdkClientInfos) {\n let rel = relative(sdkSrcDir, c.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n for (const barrel of sdkTypeBarrels) {\n let rel = relative(sdkSrcDir, barrel.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n globalFiles.push({\n relativePath: join(sdkSrcDir, 'index.ts'),\n content: `// Auto-generated barrel file\\n${rootExports.sort().join('\\n')}\\n`,\n });\n}\n\n// ─── Zod sub-generator ─────────────────────────────────────────────────────\n\nfunction collectZodOutput(\n config: ZodConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const zodBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, zodBase, config.output, '.schema.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'zod',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `zod::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateContract(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput }),\n },\n ],\n });\n }\n}\n\n// ─── Plain types sub-generator ─────────────────────────────────────────────\n\nfunction collectTypesOutput(\n config: TypesConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const typesBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, typesBase, config.output, '.types.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'plain-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `plain-types::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generatePlainTypes(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput }),\n },\n ],\n });\n }\n}\n\n// ─── Manifest IO + cleanup ─────────────────────────────────────────────────\n\nfunction readManifest(manifestPath: string): IncrementalManifest {\n if (!existsSync(manifestPath)) return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n try {\n return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n }\n}\n\n/** Write the manifest to `manifestPath`. Creates parent dirs as needed. 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\nfunction deleteStalePaths(absPaths: string[]): void {\n if (absPaths.length === 0) return;\n const removedDirs = new Set<string>();\n for (const abs of absPaths) {\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(dirname(abs));\n }\n }\n // Walk up affected dirs and remove if empty. Bounded — stops at filesystem root or first non-empty dir.\n for (const dir of removedDirs) {\n let current = dir;\n while (current.length > 1) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = dirname(current);\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n\n/** Stringify a sub-config so it can participate in fingerprints. JSON.stringify gives stable output for typical config shapes. */\nfunction stableSubConfig(config: unknown): string {\n return JSON.stringify(config ?? null);\n}\n","import { relative, dirname } from 'node:path';\nimport type {\n ContractRootNode,\n ModelNode,\n FieldNode,\n ContractTypeNode,\n ScalarTypeNode,\n ArrayTypeNode,\n TupleTypeNode,\n RecordTypeNode,\n EnumTypeNode,\n LiteralTypeNode,\n UnionTypeNode,\n DiscriminatedUnionTypeNode,\n InlineObjectTypeNode,\n IntersectionTypeNode,\n ObjectMode,\n} from '@contractkit/core';\nimport {\n collectTypeRefs,\n computeModelsWithOutput as ckComputeModelsWithOutput,\n collectExternalOutputRefs as ckCollectExternalOutputRefs,\n} from '@contractkit/core';\n\n/**\n * Maps a ContractKit object mode to its Zod constructor name.\n *\n * @returns `\"z.strictObject\"` | `\"z.object\"` | `\"z.looseObject\"`\n */\nexport function modeToWrapper(mode: ObjectMode): string {\n switch (mode) {\n case 'strict':\n return 'z.strictObject';\n case 'strip':\n return 'z.object';\n case 'loose':\n return 'z.looseObject';\n }\n}\n\n// ─── Cross-file import resolution ─────────────────────────────────────────\n\n/** Cross-file context passed to `generateContract` to wire up imports and Input/Output variant tracking. */\nexport interface ContractCodegenContext {\n /** Map from model name → absolute output file path */\n modelOutPaths: Map<string, string>;\n /** Absolute output file path for the current contract file */\n currentOutPath: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /** If set, import JsonValue from this path instead of re-declaring it (avoids barrel re-export conflicts) */\n jsonValueImportPath?: string;\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Compute which models need Input variants, including transitive dependencies.\n * A model needs an Input variant if it has visibility-modified fields, OR if\n * any of its field types (recursively) reference a model that has an Input variant.\n */\nexport function computeModelsWithInput(models: ModelNode[], externalModelsWithInput: Set<string> = new Set()): Set<string> {\n const result = new Set<string>();\n\n // Initial pass: direct visibility modifiers\n for (const model of models) {\n if (model.fields.some(f => f.visibility !== 'normal')) {\n result.add(model.name);\n }\n }\n\n // Transitive closure: add models that reference models with Input variants,\n // including through base model inheritance.\n let changed = true;\n while (changed) {\n changed = false;\n for (const model of models) {\n if (result.has(model.name)) continue;\n const refs = new Set<string>();\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // A model that extends a parent with Input variants also needs an Input variant,\n // so that the write schema can extend ParentInput instead of Parent.\n if (model.bases) for (const b of model.bases) refs.add(b);\n // A type alias (model.type set) that references a model with Input variants\n // also needs an Input variant.\n if (model.type) collectTypeRefs(model.type, refs);\n for (const ref of refs) {\n if (result.has(ref) || externalModelsWithInput.has(ref)) {\n result.add(model.name);\n changed = true;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n lines.push(` * ${model.description}`);\n }\n\n const relPath = outPath ? relative(dirname(outPath), model.loc.file) : model.loc.file;\n lines.push(` * generated from [${model.name}](file://./${relPath}#L${model.loc.line})`);\n lines.push('*/');\n return lines;\n}\n\n/**\n * Generate a TypeScript module containing Zod schemas for every model in `root`.\n *\n * Emits up to three schemas per model when visibility modifiers are present:\n * `ModelBase` (all fields), `Model` (read — no writeonly), `ModelInput` (write — no readonly).\n *\n * @param root - The parsed contract root node.\n * @param context - Optional cross-file context for import resolution and Input/Output variant tracking.\n * @returns The full TypeScript source as a string.\n */\nexport function generateContract(root: ContractRootNode, context?: ContractCodegenContext): string {\n const needsDateTime = rootNeedsDateTime(root);\n const needsDuration = rootNeedsScalar(root, 'duration');\n const needsInterval = rootNeedsScalar(root, 'interval');\n const needsBinary = rootNeedsScalar(root, 'binary');\n const needsDatetime = rootNeedsScalar(root, 'datetime');\n const needsJson = rootNeedsScalar(root, 'json');\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = ckComputeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input refs needed for Input schema fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? ckCollectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n lines.push(`import { z } from 'zod';`);\n const luxonImports: string[] = [];\n if (needsDateTime) luxonImports.push('DateTime');\n if (needsDuration) luxonImports.push('Duration');\n if (needsInterval) luxonImports.push('Interval');\n if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n lines.push(`import { ${ref} } from '${importPath}';`);\n }\n lines.push('');\n if (needsBinary) {\n lines.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (needsDatetime) {\n lines.push(\n `const _ZodDatetime = z.preprocess((val) => typeof val === 'string' ? DateTime.fromISO(val) : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be in ISO 8601 format' }));`,\n );\n }\n if (needsInterval) {\n lines.push(\n `const _ZodInterval = z.preprocess((val) => typeof val === 'string' ? Interval.fromISO(val) : val, z.custom<Interval>((val) => val instanceof Interval && val.isValid, { message: 'Must be an ISO 8601 interval' })).transform(val => val.toISO()!);`,\n );\n }\n if (needsJson) {\n lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n lines.push(\n `const _ZodJson: z.ZodType<_JsonValue> = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(_ZodJson), z.record(z.string(), _ZodJson)]));`,\n );\n }\n if (needsBinary || needsDatetime || needsInterval || needsJson) lines.push('');\n\n const modelsWithWriteonly = new Set(root.models.filter(m => m.fields.some(f => f.visibility === 'writeonly')).map(m => m.name));\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n for (const model of topoSortModels(root.models)) {\n lines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, modelsWithWriteonly, modelMap, allModelsWithOutput));\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\n/**\n * If any ancestor in the base chain has a format(input=)/format(output=) transform,\n * the parent schema compiles to a `ZodPipe` (object().transform()) which has no `.extend()`.\n * To keep extension working, inline the parent's fields into the child and inherit format/mode\n * so the child re-applies the transform on the merged shape. Returns the model unchanged when\n * no ancestor has format, preserving the existing `.extend()`-based output.\n */\nfunction flattenFormatChain(model: ModelNode, modelMap: Map<string, ModelNode>): ModelNode {\n if (!model.bases || model.bases.length === 0) return model;\n // TODO(multi-base): currently only the first base is followed for format inheritance.\n // Multi-base format flattening will need a topological merge across all bases.\n const firstBase = model.bases[0]!;\n const parent = modelMap.get(firstBase);\n if (!parent) return model;\n const flatParent = flattenFormatChain(parent, modelMap);\n const parentHasFormat =\n (flatParent.inputCase !== undefined && flatParent.inputCase !== 'camel') ||\n (flatParent.outputCase !== undefined && flatParent.outputCase !== 'camel');\n if (!parentHasFormat) return model;\n\n const merged = new Map<string, FieldNode>();\n for (const f of flatParent.fields) merged.set(f.name, f);\n for (const f of model.fields) merged.set(f.name, f);\n\n return {\n ...model,\n bases: undefined,\n fields: [...merged.values()],\n inputCase: model.inputCase ?? flatParent.inputCase,\n outputCase: model.outputCase ?? flatParent.outputCase,\n mode: model.mode ?? flatParent.mode,\n };\n}\n\nfunction generateModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithWriteonly?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n modelsWithOutput?: Set<string>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);\n }\n\n const effective = modelMap ? flattenFormatChain(model, modelMap) : model;\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = effective.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(effective.name) ?? false);\n\n const lines = needsInputSplit\n ? generateThreeSchemaModel(effective, outPath, modelsWithInput, modelsWithWriteonly, modelMap)\n : generateSimpleModel(effective, outPath);\n\n // Emit Output type alias when this model (transitively) has format(output=...)\n if (modelsWithOutput?.has(effective.name)) {\n lines.push(`export type ${effective.name}Output = z.output<typeof ${effective.name}>;`);\n }\n\n return lines;\n}\n\nfunction generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export const ${model.name} = ${renderType(model.type!)};`);\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export const ${model.name}Input = ${renderInputType(model.type!, modelsWithInput)};`);\n lines.push(`export type ${model.name}Input = z.infer<typeof ${model.name}Input>;`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = z.output<typeof ${model.name}>;`);\n }\n return lines;\n}\n\nfunction generateSimpleModel(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const { inputCase, outputCase } = model;\n const hasInputTransform = !!inputCase && inputCase !== 'camel';\n const hasOutputTransform = !!outputCase && outputCase !== 'camel';\n\n if (hasInputTransform || hasOutputTransform) {\n const inputBody =\n inputCase === 'snake'\n ? renderFieldsAsSnakeCase(model.fields, model.mode)\n : inputCase === 'pascal'\n ? renderFieldsAsPascalCase(model.fields, model.mode)\n : renderFields(model.fields, model.mode);\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...inputBody.map(l => ` ${l}`));\n lines.push(`}).transform(data => ({`);\n for (const field of model.fields) {\n const inputKey = applyCase(field.name, inputCase);\n const outputKey = applyCase(field.name, outputCase);\n const val = field.optional ? `data.${inputKey} ?? undefined` : `data.${inputKey}`;\n lines.push(` ${quoteKey(outputKey)}: ${val},`);\n }\n lines.push(`}));`);\n // When only outputCase is set, the developer-facing type is the schema's\n // pre-transform shape (camelCase). With inputCase, the post-transform\n // shape is what consumers work with.\n const typeSource = hasOutputTransform && !hasInputTransform ? 'input' : 'output';\n lines.push(`export type ${model.name} = z.${typeSource}<typeof ${model.name}>;`);\n return lines;\n }\n\n const body = renderFields(model.fields, model.mode);\n const bases = model.bases ?? [];\n if (bases.length > 0) {\n const head = bases[0]!;\n const tail = bases\n .slice(1)\n .map(b => `.extend(${b}.shape)`)\n .join('');\n lines.push(`export const ${model.name} = ${head}${tail}.extend({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n } else {\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n }\n\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n return lines;\n}\n\n/** Builds a Zod extension chain \"Head.extend(B.shape).extend(C.shape)...\" for a list of base names,\n * applying a per-base name resolver (e.g. choosing \"BaseInput\" for bases that have an Input variant). */\nfunction buildExtendChain(bases: string[], resolveName: (b: string) => string): { head: string; tail: string } {\n const head = resolveName(bases[0]!);\n const tail = bases\n .slice(1)\n .map(b => `.extend(${resolveName(b)}.shape)`)\n .join('');\n return { head, tail };\n}\n\nfunction collectEffectiveWritableFieldNames(modelName: string, modelMap: Map<string, ModelNode>): Set<string> {\n const model = modelMap.get(modelName);\n if (!model || model.type) return new Set();\n const result = new Set<string>();\n for (const base of model.bases ?? []) {\n for (const f of collectEffectiveWritableFieldNames(base, modelMap)) result.add(f);\n }\n for (const field of model.fields) {\n if (field.visibility === 'readonly') result.delete(field.name);\n else result.add(field.name);\n }\n return result;\n}\n\nfunction generateThreeSchemaModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithWriteonly?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n const lines: string[] = [];\n const name = model.name;\n\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const allFields = model.fields;\n const hasWriteonly = allFields.some(f => f.visibility === 'writeonly');\n\n const bases = model.bases ?? [];\n\n // Base schema — all fields (used internally when a submodel extends this one).\n // Only needed when this model has writeonly fields; otherwise Base === Read.\n if (hasWriteonly) {\n const baseBody = renderFields(allFields, model.mode);\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => (modelsWithWriteonly?.has(b) ? `${b}Base` : b));\n lines.push(`const ${name}Base = ${head}${tail}.extend({`);\n } else {\n lines.push(`const ${name}Base = ${wrapper}({`);\n }\n lines.push(...baseBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push('');\n }\n\n // Read schema — omit writeonly fields; extends parent read schema\n const readFields = allFields.filter(f => f.visibility !== 'writeonly');\n const readBody = renderFields(readFields, model.mode);\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => b);\n lines.push(`export const ${name} = ${head}${tail}.extend({`);\n } else {\n lines.push(`export const ${name} = ${wrapper}({`);\n }\n lines.push(...readBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name} = z.infer<typeof ${name}>;`);\n lines.push('');\n\n // Write schema — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read schema\n const writeFields = allFields.filter(f => f.visibility !== 'readonly');\n const writeBody = modelsWithInput ? renderInputFields(writeFields, modelsWithInput, model.mode) : renderFields(writeFields, model.mode);\n // Fields that become readonly in this model but were writable in a base must be omitted from\n // the base Input schema — Zod's .extend() cannot remove inherited fields.\n const fieldsToOmit = new Set<string>();\n if (bases.length > 0 && modelMap) {\n for (const field of allFields) {\n if (field.visibility === 'readonly') {\n for (const base of bases) {\n if (collectEffectiveWritableFieldNames(base, modelMap).has(field.name)) {\n fieldsToOmit.add(field.name);\n break;\n }\n }\n }\n }\n }\n const omitClause =\n fieldsToOmit.size > 0\n ? `.omit({ ${[...fieldsToOmit].map(f => `${quoteKey(f)}: true`).join(', ')} })`\n : '';\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => (modelsWithInput?.has(b) ? `${b}Input` : b));\n lines.push(`export const ${name}Input = ${head}${tail}${omitClause}.extend({`);\n } else {\n lines.push(`export const ${name}Input = ${wrapper}({`);\n }\n lines.push(...writeBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name}Input = z.infer<typeof ${name}Input>;`);\n\n return lines;\n}\n\n// ─── Fields ────────────────────────────────────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!caseTransform || caseTransform === 'camel') return name;\n if (caseTransform === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\nfunction renderFields(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderField(f, defaultMode));\n}\n\nfunction renderFieldsAsPascalCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const pascalKey = camelToPascal(f.name);\n let expr = renderType(f.type, 'pascal', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(pascalKey)}: ${expr},`;\n });\n}\n\nfunction renderFieldsAsSnakeCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const snakeKey = camelToSnake(f.name);\n let expr = renderType(f.type, 'snake', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n // .nullish() accepts null or undefined from the API; the transform coerces null → undefined\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(snakeKey)}: ${expr},`;\n });\n}\n\nfunction renderField(field: FieldNode, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderType(field.type, undefined, defaultMode);\n\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\n// ─── Type rendering ────────────────────────────────────────────────────────\n\n/**\n * Render a ContractKit AST type node as a Zod schema expression string.\n *\n * @param parseCaseTransform - When set, generates a `.transform()` that remaps incoming keys from\n * the given casing (`'snake'` | `'pascal'`) to camelCase for `inlineObject` types.\n * @param defaultMode - Fallback object mode (`'strict'` | `'strip'` | `'loose'`) when the node\n * doesn't specify its own mode.\n */\nexport function renderType(type: ContractTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderScalar(type);\n case 'array':\n return renderArray(type, parseCaseTransform, defaultMode);\n case 'tuple':\n return renderTuple(type);\n case 'record':\n return renderRecord(type);\n case 'enum':\n return renderEnum(type);\n case 'literal':\n return renderLiteral(type);\n case 'union':\n return renderUnion(type, parseCaseTransform, defaultMode);\n case 'discriminatedUnion':\n return renderDiscriminatedUnion(type, parseCaseTransform, defaultMode);\n case 'intersection':\n return renderIntersection(type, parseCaseTransform, defaultMode);\n case 'ref':\n return type.name;\n case 'lazy':\n return `z.lazy(() => ${renderType(type.inner, parseCaseTransform, defaultMode)})`;\n case 'inlineObject':\n return renderInlineObject(type, parseCaseTransform, defaultMode);\n default:\n return 'z.unknown()';\n }\n}\n\n/**\n * Render a regex source as a JS regex literal for `.regex(...)`. If the source already has\n * anchors (`^` at the start and/or an unescaped `$` at the end) we trust the user's intent\n * and emit it as-is; otherwise we wrap with `^...$` so contracts default to full-match\n * semantics. Forward slashes are always escaped since `/` is the literal delimiter.\n */\nfunction renderRegexLiteral(source: string): string {\n const body = source.replace(/\\//g, '\\\\/');\n if (regexHasAnchor(source)) return `/${body}/`;\n return `/^${body}$/`;\n}\n\nfunction regexHasAnchor(source: string): boolean {\n if (source.startsWith('^')) return true;\n if (!source.endsWith('$')) return false;\n // The trailing `$` is an anchor only if it isn't escaped — count immediately preceding\n // backslashes; an even count (including zero) means `$` is unescaped.\n let i = source.length - 2;\n let backslashes = 0;\n while (i >= 0 && source[i] === '\\\\') {\n backslashes++;\n i--;\n }\n return backslashes % 2 === 0;\n}\n\nfunction renderScalar(s: ScalarTypeNode): string {\n switch (s.name) {\n case 'string': {\n let e = 'z.string()';\n if (s.min !== undefined && s.max !== undefined) e += `.min(${s.min}).max(${s.max})`;\n else if (s.min !== undefined) e += `.min(${s.min})`;\n else if (s.max !== undefined) e += `.max(${s.max})`;\n if (s.len !== undefined) e += `.length(${s.len})`;\n if (s.regex) e += `.regex(${renderRegexLiteral(s.regex)})`;\n return e;\n }\n case 'number': {\n let e = 'z.coerce.number()';\n if (s.min !== undefined) e += `.min(${s.min})`;\n if (s.max !== undefined) e += `.max(${s.max})`;\n return e;\n }\n case 'int': {\n let e = 'z.coerce.number().int()';\n if (s.min !== undefined) e += `.min(${s.min})`;\n if (s.max !== undefined) e += `.max(${s.max})`;\n return e;\n }\n case 'bigint': {\n let inner = 'z.bigint()';\n if (s.min !== undefined) inner += `.min(${s.min}n)`;\n if (s.max !== undefined) inner += `.max(${s.max}n)`;\n return `z.preprocess((val) => typeof val === 'string' ? BigInt(val.replace(/n$/, '')) : val, ${inner})`;\n }\n case 'boolean':\n return `z.preprocess((v) => v === 'true' ? true : v === 'false' ? false : v, z.boolean())`;\n case 'date': {\n const fmt = s.format ?? 'yyyy-MM-dd';\n return `z.preprocess((val) => typeof val === 'string' ? DateTime.fromFormat(val, '${escapeString(fmt)}') : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be a date in format ${escapeString(fmt)}' }))`;\n }\n case 'time': {\n const fmt = s.format ?? 'HH:mm:ss';\n return `z.preprocess((val) => typeof val === 'string' ? DateTime.fromFormat(val, '${escapeString(fmt)}') : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be a time in format ${escapeString(fmt)}' }))`;\n }\n case 'datetime':\n return '_ZodDatetime';\n case 'interval':\n return '_ZodInterval';\n case 'duration': {\n const validParts = [`val instanceof Duration && val.isValid`];\n if (s.min !== undefined) validParts.push(`val.toMillis() >= Duration.fromISO('${s.min}').toMillis()`);\n if (s.max !== undefined) validParts.push(`val.toMillis() <= Duration.fromISO('${s.max}').toMillis()`);\n const validation = validParts.join(' && ');\n let message = 'Must be an ISO 8601 duration';\n if (s.min !== undefined && s.max !== undefined) message += ` between ${s.min} and ${s.max}`;\n else if (s.min !== undefined) message += ` of at least ${s.min}`;\n else if (s.max !== undefined) message += ` of at most ${s.max}`;\n return `z.preprocess((val) => typeof val === 'string' ? Duration.fromISO(val) : val, z.custom<Duration>((val) => ${validation}, { message: '${message}' }))`;\n }\n case 'email':\n return 'z.email()';\n case 'url':\n return 'z.url()';\n case 'uuid':\n return 'z.uuid()';\n case 'unknown':\n return 'z.unknown()';\n case 'null':\n return 'z.null()';\n case 'object':\n return 'z.record(z.string(), z.unknown())';\n case 'binary':\n return '_ZodBinary';\n case 'json':\n return '_ZodJson';\n default:\n return 'z.unknown()';\n }\n}\n\nfunction renderArray(a: ArrayTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n let e = `z.array(${renderType(a.item, parseCaseTransform, defaultMode)})`;\n if (a.min !== undefined) e += `.min(${a.min})`;\n if (a.max !== undefined) e += `.max(${a.max})`;\n return e;\n}\n\nfunction renderTuple(t: TupleTypeNode): string {\n return `z.tuple([${t.items.map(i => renderType(i)).join(', ')}])`;\n}\n\nfunction renderRecord(r: RecordTypeNode): string {\n return `z.record(${renderType(r.key)}, ${renderType(r.value)})`;\n}\n\nfunction renderEnum(e: EnumTypeNode): string {\n const vals = e.values.map(v => `\"${v}\"`).join(', ');\n return `z.enum([${vals}])`;\n}\n\nfunction renderLiteral(l: LiteralTypeNode): string {\n if (typeof l.value === 'string') return `z.literal(\"${escapeString(l.value)}\")`;\n return `z.literal(${l.value})`;\n}\n\nfunction renderUnion(u: UnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.union([${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderDiscriminatedUnion(u: DiscriminatedUnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.discriminatedUnion(\"${escapeString(u.discriminator)}\", [${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderIntersection(i: IntersectionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const [first, ...rest] = i.members;\n // When the pattern is ref & (ref | inlineObject)*, use .extend() chains to\n // produce a single ZodObject. .and() breaks strict objects — each strict side\n // rejects the other side's keys during intersection parsing, and ZodIntersection\n // has no .strict() method.\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n expr += `.extend(${member.name}.shape)`;\n } else {\n const m = member as InlineObjectTypeNode;\n const fieldLines =\n parseCaseTransform === 'snake'\n ? renderFieldsAsSnakeCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : parseCaseTransform === 'pascal'\n ? renderFieldsAsPascalCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : m.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderType(first!, parseCaseTransform, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderType(member, parseCaseTransform, defaultMode)})`;\n }\n return expr;\n}\n\nfunction renderInlineObject(o: InlineObjectTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const wrapper = modeToWrapper(o.mode ?? defaultMode ?? 'strict');\n if (parseCaseTransform === 'snake') {\n const snakeLines = renderFieldsAsSnakeCase(o.fields, defaultMode);\n const joined = snakeLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const snakeKey = camelToSnake(f.name);\n // Optional fields use .nullish() on input; coerce null → undefined in output\n const val = f.optional ? `data.${snakeKey} ?? undefined` : `data.${snakeKey}`;\n return ` ${quoteKey(f.name)}: ${val},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n if (parseCaseTransform === 'pascal') {\n const pascalLines = renderFieldsAsPascalCase(o.fields, defaultMode);\n const joined = pascalLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const pascalKey = camelToPascal(f.name);\n const val = f.optional ? `data.${pascalKey} ?? undefined` : `data.${pascalKey}`;\n return ` ${quoteKey(f.name)}: ${val},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n const fields = o.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${wrapper}({\\n${fields}\\n})`;\n}\n\n// ─── Input type rendering ─────────────────────────────────────────────────\n\n/**\n * Like renderScalar, but coerces from string input (JSON wire format).\n * Used for Input (write) schemas where data arrives as JSON strings.\n */\nfunction renderInputScalar(s: ScalarTypeNode): string {\n return renderScalar(s);\n}\n\n/**\n * Like renderType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers, and coerces scalars from strings.\n * Used for Input (write) schema fields so that sub-type references also\n * point to their Input variants.\n */\nexport function renderInputType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderInputScalar(type);\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n let e = `z.array(${renderInputType(type.item, modelsWithInput, defaultMode)})`;\n if (type.min !== undefined) e += `.min(${type.min})`;\n if (type.max !== undefined) e += `.max(${type.max})`;\n return e;\n }\n case 'tuple':\n return `z.tuple([${type.items.map(i => renderInputType(i, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'record':\n return `z.record(${renderInputType(type.key, modelsWithInput, defaultMode)}, ${renderInputType(type.value, modelsWithInput, defaultMode)})`;\n case 'union':\n return `z.union([${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'discriminatedUnion':\n return `z.discriminatedUnion(\"${escapeString(type.discriminator)}\", [${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderInputField(f, modelsWithInput ?? new Set(), defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderInputType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderInputType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'lazy':\n return `z.lazy(() => ${renderInputType(type.inner, modelsWithInput, defaultMode)})`;\n case 'inlineObject': {\n const fields = type.fields\n .flatMap(f => renderInputField(f, modelsWithInput ?? new Set(), defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n default:\n return renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderInputType(field.type, modelsWithInput, defaultMode);\n\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\nfunction renderInputFields(fields: FieldNode[], modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderInputField(f, modelsWithInput, defaultMode));\n}\n\n// ─── Query type rendering ─────────────────────────────────────────────────\n\n/**\n * Like renderType, but wraps array types with z.preprocess to handle\n * query strings where a single value arrives as a string instead of a string[].\n * Also uses Input variants for model refs when modelsWithInput is provided.\n */\nexport function renderQueryType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'array': {\n const inner = modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n return `z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner})`;\n }\n case 'inlineObject': {\n const fields = type.fields.map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`).join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderQueryType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderQueryType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n default:\n return modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderQueryField(field: FieldNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n let expr =\n field.type.kind === 'array'\n ? renderQueryType(field.type, modelsWithInput, defaultMode)\n : modelsWithInput\n ? renderInputType(field.type, modelsWithInput, defaultMode)\n : renderType(field.type, undefined, defaultMode);\n\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n\n return `${quoteKey(field.name)}: ${expr},`;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\nfunction quoteKey(name: string): string {\n return isValidIdentifier(name) ? name : `'${name}'`;\n}\n\n// ─── String escaping ──────────────────────────────────────────────────────\n\nfunction escapeString(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r');\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction rootNeedsDateTime(root: ContractRootNode): boolean {\n return root.models.some(m => (m.type && typeNeedsDateTime(m.type)) || m.fields.some(f => typeNeedsDateTime(f.type)));\n}\n\n/** Returns true if `type` (recursively) contains a scalar with the given `name`. */\nexport function typeNeedsScalar(type: ContractTypeNode, name: string): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === name;\n case 'array':\n return typeNeedsScalar(type.item, name);\n case 'tuple':\n return type.items.some(i => typeNeedsScalar(i, name));\n case 'record':\n return typeNeedsScalar(type.key, name) || typeNeedsScalar(type.value, name);\n case 'union':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'discriminatedUnion':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'intersection':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'lazy':\n return typeNeedsScalar(type.inner, name);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsScalar(f.type, name));\n default:\n return false;\n }\n}\n\n/** Returns true if any model in `root` uses a scalar with the given `name`. */\nexport function rootNeedsScalar(root: ContractRootNode, name: string): boolean {\n return root.models.some(m => (m.type && typeNeedsScalar(m.type, name)) || m.fields.some(f => typeNeedsScalar(f.type, name)));\n}\n\n/** Returns true if `type` (recursively) contains a `date`, `time`, or `datetime` scalar. */\nexport function typeNeedsDateTime(type: ContractTypeNode): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === 'date' || type.name === 'time' || type.name === 'datetime';\n case 'array':\n return typeNeedsDateTime(type.item);\n case 'union':\n return type.members.some(typeNeedsDateTime);\n case 'discriminatedUnion':\n return type.members.some(typeNeedsDateTime);\n case 'intersection':\n return type.members.some(typeNeedsDateTime);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsDateTime(f.type));\n default:\n return false;\n }\n}\n\n/** Collect model names referenced in `root` that are not defined locally (need to be imported). */\nexport function collectExternalRefs(root: ContractRootNode): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (model.bases?.[0] && !localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n }\n\n for (const name of localNames) refs.delete(name);\n return [...refs].sort();\n}\n\n/** Collect external Input variant refs needed for Input schema fields. */\nexport function collectExternalInputRefs(root: ContractRootNode, modelsWithInput: Set<string>): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (!modelsWithInput.has(model.name)) continue;\n // Type alias: collect Input refs from the aliased type expression.\n if (model.type) {\n collectInputTypeRefs(model.type, refs, modelsWithInput);\n continue;\n }\n // When a model extends an external parent that has an Input variant,\n // the write schema extends ParentInput — so we need to import it.\n if (model.bases?.[0] && modelsWithInput.has(model.bases?.[0]) && !localNames.has(model.bases?.[0])) {\n refs.add(`${model.bases?.[0]}Input`);\n }\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n for (const field of writeFields) {\n collectInputTypeRefs(field.type, refs, modelsWithInput);\n }\n }\n\n // Remove locally defined Input variants (generated in this file)\n for (const name of localNames) {\n refs.delete(`${name}Input`);\n }\n\n return [...refs].sort();\n}\n\nfunction collectInputTypeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(i => collectInputTypeRefs(i, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeRefs(type.key, out, modelsWithInput);\n collectInputTypeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\n/**\n * Topologically sort models so dependencies are emitted before dependents.\n * Falls back to source order for cycles (which would need z.lazy at runtime).\n */\nexport function topoSortModels(models: ModelNode[]): ModelNode[] {\n const localNames = new Set(models.map(m => m.name));\n const modelMap = new Map(models.map(m => [m.name, m]));\n\n // Build adjacency: model name → set of local model names it depends on\n const deps = new Map<string, Set<string>>();\n for (const model of models) {\n const refs = new Set<string>();\n if (model.bases?.[0] && localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // Keep only local dependencies\n const localDeps = new Set<string>();\n for (const r of refs) {\n if (localNames.has(r) && r !== model.name) localDeps.add(r);\n }\n deps.set(model.name, localDeps);\n }\n\n // Kahn's algorithm\n const inDegree = new Map<string, number>();\n for (const name of localNames) inDegree.set(name, 0);\n for (const [, d] of deps) {\n for (const dep of d) {\n inDegree.set(dep, (inDegree.get(dep) ?? 0) + 1);\n }\n }\n\n // Note: inDegree counts how many models *depend on* this model,\n // but for Kahn's we need how many dependencies each model has.\n // Re-do: inDegree = number of unresolved deps for each model.\n const remaining = new Map<string, Set<string>>();\n for (const [name, d] of deps) {\n remaining.set(name, new Set(d));\n }\n\n const queue: string[] = [];\n for (const name of localNames) {\n if (remaining.get(name)!.size === 0) queue.push(name);\n }\n\n const sorted: ModelNode[] = [];\n while (queue.length > 0) {\n const name = queue.shift()!;\n sorted.push(modelMap.get(name)!);\n // Remove this model from all dependents' remaining sets\n for (const [other, rem] of remaining) {\n if (rem.delete(name) && rem.size === 0) {\n queue.push(other);\n }\n }\n }\n\n // Append any models not yet emitted (cycles)\n for (const model of models) {\n if (!sorted.includes(model)) sorted.push(model);\n }\n\n return sorted;\n}\n\n/**\n * Resolve the import path for an external model reference.\n * When a codegen context is available, computes the correct relative path\n * from the current file to the referenced model's output file.\n * Falls back to same-directory PascalCase → dot.case convention.\n */\nexport function resolveImportPath(refName: string, context?: ContractCodegenContext): string {\n if (context) {\n const refOutPath = context.modelOutPaths.get(refName);\n if (refOutPath) {\n const fromDir = dirname(context.currentOutPath);\n let rel = relative(fromDir, refOutPath);\n // Replace .ts extension with .js for ESM imports\n rel = rel.replace(/\\.ts$/, '.js');\n // Ensure relative path starts with ./ or ../\n if (!rel.startsWith('.')) rel = './' + rel;\n return rel;\n }\n }\n // Fallback: assume same directory, use PascalCase → dot.case convention\n const moduleName = pascalToDotCase(refName);\n return `./${moduleName}.js`;\n}\n\n/** Convert PascalCase to dot-separated lowercase: CounterpartyAccount → counterparty.account */\nexport function pascalToDotCase(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/g, '$1.$2').toLowerCase();\n}\n","import type { OpRootNode, OpRouteNode, OpOperationNode, ContractTypeNode, ParamSource, ObjectMode } from '@contractkit/core';\nimport { resolveModifiers, resolveSecurity, SECURITY_NONE, classifyContentType } from '@contractkit/core';\nimport {\n renderType,\n renderInputType,\n renderQueryType,\n pascalToDotCase,\n typeNeedsDateTime,\n typeNeedsScalar,\n modeToWrapper,\n} from './codegen-contract.js';\nimport { renderOutputTsType, quoteKey, headerNameToProperty } from './ts-render.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Content-type helpers ──────────────────────────────────────────────────\n\n/** Map a request MIME type to the koa-bodyparser parser token used in middleware. */\nfunction bodyParserToken(contentType: string): string {\n switch (classifyContentType(contentType)) {\n case 'urlencoded':\n return 'urlencoded';\n case 'multipart':\n return 'multipart';\n case 'text':\n return 'text';\n case 'binary':\n // koa-bodyparser has no native binary token; fall back to text so the body is\n // still readable as a string. Services handling binary uploads should switch to\n // multipart/form-data.\n return 'text';\n default:\n return 'json';\n }\n}\n\n/**\n * Deep structural equality on ContractTypeNode, ignoring source locations on inline fields.\n * Used to decide whether multiple declared request MIMEs can share a single validate path.\n */\nexport function bodyTypesStructurallyEqual(a: ContractTypeNode, b: ContractTypeNode): boolean {\n if (a.kind !== b.kind) return false;\n switch (a.kind) {\n case 'scalar': {\n const bb = b as typeof a;\n return a.name === bb.name && a.min === bb.min && a.max === bb.max && a.len === bb.len && a.regex === bb.regex && a.format === bb.format;\n }\n case 'array': {\n const bb = b as typeof a;\n return a.min === bb.min && a.max === bb.max && bodyTypesStructurallyEqual(a.item, bb.item);\n }\n case 'tuple': {\n const bb = b as typeof a;\n return a.items.length === bb.items.length && a.items.every((x, i) => bodyTypesStructurallyEqual(x, bb.items[i]!));\n }\n case 'record': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.key, bb.key) && bodyTypesStructurallyEqual(a.value, bb.value);\n }\n case 'enum': {\n const bb = b as typeof a;\n return a.values.length === bb.values.length && a.values.every((v, i) => v === bb.values[i]);\n }\n case 'literal': {\n const bb = b as typeof a;\n return a.value === bb.value;\n }\n case 'union':\n case 'intersection': {\n const bb = b as typeof a;\n return a.members.length === bb.members.length && a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!));\n }\n case 'discriminatedUnion': {\n const bb = b as typeof a;\n return (\n a.discriminator === bb.discriminator &&\n a.members.length === bb.members.length &&\n a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!))\n );\n }\n case 'ref': {\n const bb = b as typeof a;\n return a.name === bb.name && !!a.lazy === !!bb.lazy;\n }\n case 'lazy': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.inner, bb.inner);\n }\n case 'inlineObject': {\n const bb = b as typeof a;\n if (a.mode !== bb.mode) return false;\n if (a.fields.length !== bb.fields.length) return false;\n return a.fields.every((f, i) => {\n const g = bb.fields[i]!;\n return (\n f.name === g.name &&\n f.optional === g.optional &&\n f.nullable === g.nullable &&\n f.visibility === g.visibility &&\n f.default === g.default &&\n !!f.deprecated === !!g.deprecated &&\n bodyTypesStructurallyEqual(f.type, g.type)\n );\n });\n }\n }\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\nexport interface OpCodegenOptions {\n servicePathTemplate?: string;\n typeImportPathTemplate?: string;\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /**\n * Whether to emit handlers for operations marked `internal`. Defaults to `true` because\n * the server still needs routes for internal endpoints; set to `false` to omit them\n * from the generated router entirely.\n */\n includeInternal?: boolean;\n}\n\n/** Generate a Koa router module for every operation in `root`, including the imports, type aliases, and handler list. */\nexport function generateOp(root: OpRootNode, options: OpCodegenOptions = {}): string {\n // Collect all referenced types across all routes\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput);\n const services = collectServices(root);\n const routerName = deriveRouterName(root.file);\n const needsParseAndValidate = routeNeedsValidation(root);\n\n // Generate the body first so we can detect whether `z.` is actually referenced\n // before deciding whether to emit the zod import.\n const body: string[] = [];\n const needsSignature = fileNeedsSignature(root);\n const needsSecurity = fileNeedsSecurity(root);\n const koaImports = ['ServerKitRouter', 'bodyParserMiddleware'];\n if (needsSecurity) koaImports.push('requireSecurity');\n if (needsSignature) koaImports.push('requireSignature');\n body.push(`import { ${koaImports.join(', ')} } from '@maroonedsoftware/koa';`);\n\n for (const svc of services) {\n const modulePath = root.services?.[svc] ?? root.meta[svc] ?? deriveModulePath(svc, options.servicePathTemplate);\n body.push(`import { ${svc} } from '${modulePath}';`);\n }\n\n if (types.length > 0) {\n body.push(...generateTypeImports(types, root.file, options));\n }\n\n if (opNeedsDateTime(root)) {\n body.push(`import { DateTime } from 'luxon';`);\n }\n\n if (needsParseAndValidate) {\n body.push(`import { parseAndValidate } from '@maroonedsoftware/zod';`);\n }\n\n const helpers: string[] = [];\n if (opNeedsScalar(root, 'binary')) {\n helpers.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (opNeedsScalar(root, 'datetime')) {\n helpers.push(\n `const _ZodDatetime = z.preprocess((val) => typeof val === 'string' ? DateTime.fromISO(val) : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be in ISO 8601 format' }));`,\n );\n }\n if (opNeedsScalar(root, 'json')) {\n helpers.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n helpers.push(\n `const _ZodJson: z.ZodType<_JsonValue> = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(_ZodJson), z.record(z.string(), _ZodJson)]));`,\n );\n }\n\n const lines: string[] = [];\n\n lines.push('');\n lines.push('/**');\n const relFile = options.outPath ? relative(dirname(options.outPath), root.file) : root.file;\n lines.push(` * generated from [${basename(root.file)}](file://./${relFile})`);\n lines.push('*/');\n lines.push(`export const ${routerName} = ServerKitRouter();`);\n lines.push('');\n\n const includeInternal = options.includeInternal ?? true;\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n lines.push(...generateHandler(route, op, root, options));\n lines.push('');\n }\n }\n\n const allContent = [...body, ...(helpers.length ? ['', ...helpers] : []), ...lines].join('\\n');\n const needsZod = /\\bz\\./.test(allContent);\n return (needsZod ? `import { z } from 'zod';\\n` : '') + allContent;\n}\n\n// ─── Handler generation ────────────────────────────────────────────────────\n\nfunction generateHandler(route: OpRouteNode, op: OpOperationNode, root: OpRootNode, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const file = root.file;\n const outPath = options.outPath;\n const modelsWithInput = options.modelsWithInput;\n\n lines.push('/**');\n\n // JSDoc from description\n const desc = op.description ?? route.description;\n if (desc) {\n lines.push(` * ${desc}`);\n }\n // Source location comment\n const relFile = outPath ? relative(dirname(outPath), file) : file;\n lines.push(` * from [${basename(file)}](file://./${relFile}#L${op.loc.line})`);\n\n // Security annotation (operation-level wins; falls back to route → file level)\n const effectiveSecurity = resolveSecurity(route, op, root);\n if (effectiveSecurity === SECURITY_NONE) {\n lines.push(` * anonymous access, no security required`);\n }\n\n // Modifier annotations\n const mods = resolveModifiers(route, op);\n if (mods.includes('internal')) lines.push(` * @internal`);\n if (mods.includes('deprecated')) lines.push(` * @deprecated`);\n\n lines.push('*/');\n\n const method = op.method;\n const path = route.path.replace(/\\{(\\w+)\\}/g, ':$1');\n const bodies = op.request?.bodies ?? [];\n const hasBody = bodies.length > 0;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n\n // Middleware list\n const middlewares: string[] = [];\n if (effectiveSecurity !== SECURITY_NONE) {\n const args = effectiveSecurity && effectiveSecurity.requireMfa !== undefined ? `{ requireMfa: ${effectiveSecurity.requireMfa} }` : '';\n middlewares.push(`requireSecurity(${args})`);\n }\n if (hasBody) {\n const parserTokens = Array.from(new Set(bodies.map(b => bodyParserToken(b.contentType))));\n const tokensExpr = parserTokens.map(t => `'${t}'`).join(', ');\n middlewares.push(`bodyParserMiddleware([${tokensExpr}])`);\n }\n if (op.signature) {\n middlewares.push(`requireSignature('${op.signature}')`);\n }\n const middlewareStr = middlewares.length > 0 ? `, ${middlewares.join(', ')},` : ',';\n\n lines.push(`${deriveRouterName(file)}.${method}('${path}'${middlewareStr} async (ctx, next) => {`);\n\n // Params / query / headers validation (request-side — use Input variants)\n lines.push(...generateParamValidation(route.params, 'ctx.params', 'params', route.paramsMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.query, 'ctx.query', 'query', op.queryMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.headers, 'ctx.headers', 'headers', op.headersMode ?? 'strip', '', modelsWithInput));\n\n // Body validation (request-side — use Input variants)\n if (hasBody && op.request) {\n if (isSingleMultipart) {\n lines.push(` const multipartBody = ctx.body as MultipartBody;`);\n lines.push('');\n } else if (bodies.length === 1) {\n lines.push(` const body = await parseAndValidate(ctx.body, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n // All declared MIMEs share the same body shape — single validation suffices\n lines.push(` const body = await parseAndValidate(ctx.body, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else {\n // Different body types per MIME — dispatch on Content-Type\n const annotation = bodies\n .map(b =>\n b.contentType === 'multipart/form-data' ? 'MultipartBody' : `z.infer<typeof ${renderInputType(b.bodyType, modelsWithInput)}>`,\n )\n .join(' | ');\n lines.push(` let body!: ${annotation};`);\n lines.push(` switch (ctx.request.type) {`);\n for (const b of bodies) {\n lines.push(` case '${b.contentType}':`);\n if (b.contentType === 'multipart/form-data') {\n lines.push(` body = ctx.body as MultipartBody;`);\n } else {\n lines.push(` body = await parseAndValidate(ctx.body, ${renderInputType(b.bodyType, modelsWithInput)});`);\n }\n lines.push(` break;`);\n }\n lines.push(` }`);\n lines.push('');\n }\n }\n\n // Service call — use the first response with a body as the primary response\n const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];\n const serviceParts = inferService(op, route, file);\n const respHeaders = primaryResponse?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersAnnotation = hasRespHeaders\n ? `{ ${respHeaders\n .map(h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, options.modelsWithOutput)}`)\n .join('; ')} }`\n : '';\n\n if (primaryResponse?.bodyType) {\n const { annotation, prelude } = formatTypeAnnotation(primaryResponse.bodyType!, options.modelsWithOutput);\n if (prelude) {\n lines.push(` ${prelude}`);\n }\n lines.push(` const service = ctx.container.get(${serviceParts.className});`);\n if (hasRespHeaders) {\n lines.push(\n ` const result: { body: ${annotation}; headers: ${headersAnnotation} } = await service.${serviceParts.methodName}(${buildArgs(route, op)});`,\n );\n } else {\n lines.push(` const result: ${annotation} = await service.${serviceParts.methodName}(${buildArgs(route, op)});`);\n }\n } else {\n lines.push(` const service = ctx.container.get(${serviceParts.className});`);\n if (hasRespHeaders) {\n lines.push(` const result: { headers: ${headersAnnotation} } = await service.${serviceParts.methodName}(${buildArgs(route, op)});`);\n } else {\n lines.push(` await service.${serviceParts.methodName}(${buildArgs(route, op)});`);\n }\n }\n\n lines.push('');\n lines.push(` ctx.status = ${primaryResponse?.statusCode ?? 200};`);\n\n if (hasRespHeaders) {\n for (const h of respHeaders) {\n const accessor = `result.headers[${JSON.stringify(headerNameToProperty(h.name))}]`;\n if (h.optional) {\n lines.push(` if (${accessor} !== undefined) ctx.set('${h.name}', String(${accessor}));`);\n } else {\n lines.push(` ctx.set('${h.name}', String(${accessor}));`);\n }\n }\n }\n\n if (primaryResponse?.bodyType && primaryResponse.contentType) {\n lines.push(` ctx.type = '${primaryResponse.contentType}';`);\n lines.push(` ctx.body = ${hasRespHeaders ? 'result.body' : 'result'};`);\n }\n\n lines.push('');\n lines.push(` await next();`);\n lines.push(`});`);\n\n return lines;\n}\n\n// ─── Inference helpers ─────────────────────────────────────────────────────\n\nfunction inferService(op: OpOperationNode, route: OpRouteNode, file: string): { className: string; methodName: string } {\n // If explicitly declared: service: ServiceClass.methodName\n if (op.service) {\n const [cls = '', method] = op.service.split('.');\n return { className: cls, methodName: method ?? 'handle' };\n }\n\n // Infer from file name + method + path\n const baseName = deriveBaseName(file); // e.g. \"ledger.categories\" -> \"LedgerCategories\"\n const className = `${baseName}Service`;\n const methodName = inferMethodName(op.method, route.path);\n return { className, methodName };\n}\n\nfunction inferMethodName(method: string, path: string): string {\n const hasParam = path.includes('{');\n switch (method) {\n case 'get':\n return hasParam ? 'getById' : 'list';\n case 'post':\n return 'create';\n case 'put':\n return 'replace';\n case 'patch':\n return 'update';\n case 'delete':\n return 'delete';\n default:\n return 'handle';\n }\n}\n\nfunction buildArgs(route: OpRouteNode, op: OpOperationNode): string {\n const args: string[] = [];\n // Path params: spread individually (inline) or pass 'params' object (type-ref/ContractTypeNode)\n if (route.params) {\n if (route.params.kind === 'params') {\n args.push(...route.params.nodes.map(p => p.name));\n } else {\n args.push('params');\n }\n }\n // Body\n if (op.request && op.request.bodies.length > 0) {\n const bodies = op.request.bodies;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n args.push(isSingleMultipart ? 'multipartBody' : 'body');\n }\n // Query\n if (op.query) args.push('query');\n // Headers\n if (op.headers) args.push('headers');\n return args.join(', ');\n}\n\nfunction formatTypeAnnotation(bodyType: ContractTypeNode, modelsWithOutput?: Set<string>): { annotation: string; prelude?: string } {\n if (bodyType.kind === 'array') {\n const inner = formatTypeAnnotation(bodyType.item, modelsWithOutput);\n return { annotation: `${inner.annotation}[]`, prelude: inner.prelude };\n }\n if (bodyType.kind === 'ref') {\n const name = modelsWithOutput?.has(bodyType.name) ? `${bodyType.name}Output` : bodyType.name;\n return { annotation: name };\n }\n if (bodyType.kind === 'scalar') return { annotation: bodyType.name };\n // For complex types, extract schema into a variable so the result line stays readable\n const schema = renderType(bodyType);\n return {\n annotation: 'z.infer<typeof resultType>',\n prelude: `const resultType = ${schema};`,\n };\n}\n\nfunction generateParamValidation(\n source: ParamSource | undefined,\n ctxExpr: string,\n varName: string,\n mode: ObjectMode,\n suffix = '',\n modelsWithInput?: Set<string>,\n): string[] {\n if (!source) return [];\n const lines: string[] = [];\n const isQuery = ctxExpr === 'ctx.query';\n if (source.kind === 'ref') {\n // Type reference — apply mode as a method call on the schema\n const typeName = modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;\n lines.push(` const ${varName} = await parseAndValidate(${ctxExpr}, ${typeName}.${mode}());`);\n lines.push('');\n } else if (source.kind === 'params') {\n // Inline param declarations — wrap with the appropriate z.*Object constructor\n if (source.nodes.length > 0) {\n // Destructure only for params (spread individually in service call);\n // query/headers are passed as whole objects.\n const lhs = varName === 'params' ? `{ ${source.nodes.map(p => p.name).join(', ')} }` : varName;\n lines.push(` const ${lhs} = await parseAndValidate(`);\n lines.push(` ${ctxExpr},`);\n lines.push(` ${modeToWrapper(mode)}({`);\n for (const param of source.nodes) {\n const key = isValidIdentifier(param.name) ? param.name : `'${param.name}'`;\n if (isQuery && param.type.kind === 'array') {\n const inner = renderType(param.type);\n lines.push(` ${key}: z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner}),`);\n } else {\n lines.push(` ${key}: ${renderType(param.type)},`);\n }\n }\n lines.push(` })${suffix},`);\n lines.push(` );`);\n lines.push('');\n }\n } else {\n // ContractTypeNode — use query-aware rendering for query params (coerces single string → array),\n // otherwise use Input variant rendering; apply mode as a method call\n const schema = isQuery ? renderQueryType(source.node, modelsWithInput) : renderInputType(source.node, modelsWithInput);\n lines.push(` const ${varName} = await parseAndValidate(${ctxExpr}, (${schema}).${mode}());`);\n lines.push('');\n }\n return lines;\n}\n\n// ─── Type import resolution ────────────────────────────────────────────────\n\n/**\n * Generate per-file type import statements.\n * When modelOutPaths is available, groups types by their actual output file\n * and computes correct relative paths. Falls back to the template-based\n * single-import approach for types not found in the map.\n */\nfunction generateTypeImports(types: string[], opFile: string, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n // Group types by their output file\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n // Emit one import per source file with a relative path\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import { ${names.sort().join(', ')} } from '${rel}';`);\n }\n\n // Fallback for types not in the map\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import { ${type} } from './${moduleName}.js';`);\n }\n } else {\n // No resolution context — fall back to template-based single import\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\n// ─── Collection helpers ────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of route.operations) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n if (resp.bodyType) {\n collectTypeNodeRefs(resp.bodyType, types);\n collectOutputTypeNodeRefs(resp.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'tuple':\n type.items.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'record':\n collectOutputTypeNodeRefs(type.key, out, modelsWithOutput);\n collectOutputTypeNodeRefs(type.value, out, modelsWithOutput);\n break;\n case 'union':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'intersection':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'type') {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeNodeRefs(type.key, out, modelsWithInput);\n collectInputTypeNodeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\nfunction paramSourceNeedsDateTime(source: ParamSource | undefined): boolean {\n if (!source) return false;\n if (source.kind === 'ref') return false;\n if (source.kind === 'params') return source.nodes.some(p => typeNeedsDateTime(p.type));\n return typeNeedsDateTime(source.node);\n}\n\nfunction opNeedsDateTime(root: OpRootNode): boolean {\n return root.routes.some(\n route =>\n paramSourceNeedsDateTime(route.params) ||\n route.operations.some(\n op =>\n !!op.request?.bodies.some(b => typeNeedsDateTime(b.bodyType)) ||\n op.responses.some(r => r.bodyType && typeNeedsDateTime(r.bodyType)) ||\n paramSourceNeedsDateTime(op.query) ||\n paramSourceNeedsDateTime(op.headers),\n ),\n );\n}\n\nfunction paramSourceNeedsScalar(source: ParamSource | undefined, name: string): boolean {\n if (!source) return false;\n if (source.kind === 'ref') return false;\n if (source.kind === 'params') return source.nodes.some(p => typeNeedsScalar(p.type, name));\n return typeNeedsScalar(source.node, name);\n}\n\nfunction opNeedsScalar(root: OpRootNode, name: string): boolean {\n return root.routes.some(\n route =>\n paramSourceNeedsScalar(route.params, name) ||\n route.operations.some(\n op =>\n !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, name)) ||\n op.responses.some(r => r.bodyType && typeNeedsScalar(r.bodyType, name)) ||\n paramSourceNeedsScalar(op.query, name) ||\n paramSourceNeedsScalar(op.headers, name),\n ),\n );\n}\n\nfunction collectServices(root: OpRootNode): string[] {\n const services = new Set<string>();\n const inferredService = `${deriveBaseName(root.file)}Service`;\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (op.service) {\n services.add(op.service.split('.')[0] ?? op.service);\n } else {\n services.add(inferredService);\n }\n }\n }\n return [...services].sort();\n}\n\nfunction hasParamSource(source?: ParamSource): boolean {\n if (!source) return false;\n if (source.kind === 'ref') return true;\n if (source.kind === 'params') return source.nodes.length > 0;\n return true; // type\n}\n\nfunction routeNeedsValidation(root: OpRootNode): boolean {\n return root.routes.some(\n r => hasParamSource(r.params) || r.operations.some(op => !!op.request || hasParamSource(op.query) || hasParamSource(op.headers)),\n );\n}\n\nfunction fileNeedsSecurity(root: OpRootNode): boolean {\n return root.routes.some(route => route.operations.some(op => resolveSecurity(route, op, root) !== SECURITY_NONE));\n}\n\nfunction fileNeedsSignature(root: OpRootNode): boolean {\n return root.routes.some(route => route.operations.some(op => !!op.signature));\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\nfunction deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n // ledger.categories -> LedgerCategories\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction deriveRouterName(file: string): string {\n return `${deriveBaseName(file)}Router`;\n}\n\nfunction deriveModulePath(serviceName: string, template?: string): string {\n // LedgerService -> #modules/ledger/ledger.service.js\n const base = serviceName.replace(/Service$/, '');\n const kebab = base.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`).replace(/^-/, '');\n if (template) {\n return template.replace(/\\{name\\}/g, base).replace(/\\{kebab\\}/g, kebab);\n }\n return `#modules/${kebab}/${kebab}.service.js`;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n","import type { ContractTypeNode, FieldNode } from '@contractkit/core';\n\nexport const JSON_VALUE_TYPE_DECL = 'export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };';\n\nexport function quoteKey(name: string): string {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? name : `'${name}'`;\n}\n\n/** Convert an HTTP header name (e.g. `preference-applied`, `X-Request-ID`, `ETag`) to camelCase for use as a JS property. */\nexport function headerNameToProperty(name: string): string {\n const parts = name.split(/[-_]/).filter(Boolean);\n return parts\n .map((p, i) => {\n const lower = p.toLowerCase();\n return i === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);\n })\n .join('');\n}\n\n// ─── TypeScript type rendering ────────────────────────────────────────────\n\nexport function renderTsType(type: ContractTypeNode): string {\n switch (type.kind) {\n case 'scalar':\n return renderTsScalar(type.name);\n case 'array': {\n const inner = renderTsType(type.item);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'tuple':\n return `[${type.items.map(renderTsType).join(', ')}]`;\n case 'record':\n return `Record<${renderTsType(type.key)}, ${renderTsType(type.value)}>`;\n case 'enum':\n return type.values.map(v => `'${v}'`).join(' | ');\n case 'literal':\n return typeof type.value === 'string' ? `'${type.value}'` : String(type.value);\n case 'union':\n return type.members.map(renderTsType).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(renderTsType).join(' | ');\n case 'intersection':\n return type.members.map(renderTsType).join(' & ');\n case 'ref':\n return type.name;\n case 'lazy':\n return renderTsType(type.inner);\n case 'inlineObject':\n return renderTsInlineObject(type.fields);\n default:\n return 'unknown';\n }\n}\n\nfunction renderTsScalar(name: string): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n return 'string';\n case 'number':\n case 'int':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'datetime':\n case 'duration':\n case 'interval':\n return 'string';\n case 'null':\n return 'null';\n case 'unknown':\n return 'unknown';\n case 'object':\n return 'Record<string, unknown>';\n case 'binary':\n return 'Blob';\n case 'json':\n return 'JsonValue';\n default:\n return 'unknown';\n }\n}\n\nfunction renderTsInlineObject(fields: FieldNode[]): string {\n const entries = fields.map(f => {\n const opt = f.optional ? '?' : '';\n return `${quoteKey(f.name)}${opt}: ${renderTsType(f.type)}`;\n });\n return `{ ${entries.join('; ')} }`;\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers. Used for request-side types\n * (body, params, query, headers).\n */\nexport function renderInputTsType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {\n if (!modelsWithInput || modelsWithInput.size === 0) return renderTsType(type);\n switch (type.kind) {\n case 'ref':\n return modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n const inner = renderInputTsType(type.item, modelsWithInput);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' & ');\n case 'union':\n return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderInputTsType(f.type, modelsWithInput)}`).join('; ')} }`;\n case 'lazy':\n return renderInputTsType(type.inner, modelsWithInput);\n default:\n return renderTsType(type);\n }\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Output variant\n * (post-transform wire shape) when the model has format(output=...) or\n * transitively references one. Used for response-side types in routers\n * and SDK return types.\n */\nexport function renderOutputTsType(type: ContractTypeNode, modelsWithOutput?: Set<string>): string {\n if (!modelsWithOutput || modelsWithOutput.size === 0) return renderTsType(type);\n switch (type.kind) {\n case 'ref':\n return modelsWithOutput.has(type.name) ? `${type.name}Output` : type.name;\n case 'array': {\n const inner = renderOutputTsType(type.item, modelsWithOutput);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' & ');\n case 'union':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderOutputTsType(f.type, modelsWithOutput)}`).join('; ')} }`;\n case 'lazy':\n return renderOutputTsType(type.inner, modelsWithOutput);\n default:\n return renderTsType(type);\n }\n}\n","import type { OpRootNode, OpRouteNode, OpOperationNode, OpRequestBodyNode, ContractTypeNode, ParamSource } from '@contractkit/core';\nimport { resolveModifiers, isJsonMime, classifyContentType } from '@contractkit/core';\nimport { renderInputTsType, renderOutputTsType, quoteKey, headerNameToProperty, JSON_VALUE_TYPE_DECL } from './ts-render.js';\nimport { pascalToDotCase, typeNeedsScalar } from './codegen-contract.js';\nimport { bodyTypesStructurallyEqual } from './codegen-operation.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Body strategy ────────────────────────────────────────────────────────\n\ntype BodyStrategy =\n | { kind: 'none' }\n | { kind: 'single'; body: OpRequestBodyNode }\n | { kind: 'multi-equal'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-formdata-detect'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-required-arg'; bodies: OpRequestBodyNode[] };\n\n/** Serialize expression for a single MIME, given the source body var (e.g. 'body'). */\nfunction jsonOrFormSerialize(varName: string, contentType: string): string {\n if (contentType === 'application/x-www-form-urlencoded') {\n return `new URLSearchParams(${varName} as unknown as Record<string, string>).toString()`;\n }\n if (contentType === 'multipart/form-data') {\n return `(${varName} as FormData)`;\n }\n // application/json + any `+json` structured suffix — JSON.stringify with bigint support.\n return `JSON.stringify(${varName}, bigIntReplacer)`;\n}\n\n/**\n * Build a runtime expression that picks the right serialization based on a contentType variable.\n * Used by the SDK when the caller passes (or defaults to) a content-type at call time.\n */\nfunction renderSerializeExpr(varName: string, bodies: OpRequestBodyNode[], ctVar: string): string {\n // Build a chained ternary, last MIME is the fallback\n const arms = bodies.slice(0, -1);\n const last = bodies[bodies.length - 1]!;\n let expr = jsonOrFormSerialize(varName, last.contentType);\n for (let i = arms.length - 1; i >= 0; i--) {\n const arm = arms[i]!;\n expr = `${ctVar} === '${arm.contentType}' ? ${jsonOrFormSerialize(varName, arm.contentType)} : ${expr}`;\n }\n return expr;\n}\n\nfunction classifyBodyStrategy(op: OpOperationNode): BodyStrategy {\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 0) return { kind: 'none' };\n if (bodies.length === 1) return { kind: 'single', body: bodies[0]! };\n if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n return { kind: 'multi-equal', bodies };\n }\n if (bodies.some(b => b.contentType === 'multipart/form-data')) {\n return { kind: 'multi-formdata-detect', bodies };\n }\n return { kind: 'multi-required-arg', bodies };\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/** Options shared by every SDK code-generation entry point. */\nexport interface SdkCodegenOptions {\n /** Template for type import paths when `modelOutPaths` is not provided. Supports `{module}` and `{base}`. */\n typeImportPathTemplate?: string;\n /** Absolute path of the file currently being generated. Used to compute relative imports. */\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Absolute path to the shared sdk-options.ts file (if set, imports SdkOptions instead of defining inline) */\n sdkOptionsPath?: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /**\n * Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —\n * internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`\n * to include them (e.g. for an internal-use SDK).\n */\n includeInternal?: boolean;\n /**\n * Override the generated client class name. When omitted, falls back to\n * `deriveClientClassName(root.file)` (the legacy per-file name). The aggregator\n * uses this to emit `<Area><Subarea>Client` for area+subarea leaf files.\n */\n clientClassName?: string;\n}\n\n/**\n * Returns true if the root contains at least one operation eligible for SDK emission.\n * With `includeInternal: false` (default) that means at least one non-internal op; with\n * `includeInternal: true` any op qualifies.\n */\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\n/**\n * Generate a complete `*.client.ts` file for one operation root: imports, the client class\n * declaration, and one method per public operation. Used for top-level (no-area) files and\n * for subarea-leaf files. Area-level files are NOT routed through this — their methods get\n * inlined into the SDK aggregator via {@link generateClientMethods} + {@link generateSdkAggregator}.\n */\nexport function generateSdk(root: OpRootNode, options: SdkCodegenOptions = {}): string {\n const lines: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput, includeInternal);\n const clientClassName = options.clientClassName ?? deriveClientClassName(root.file);\n\n // Type-only imports\n if (types.length > 0) {\n lines.push(...generateTypeImports(types, root.file, options));\n }\n\n // SdkOptions import (from shared file) or inline fallback\n if (options.sdkOptionsPath && options.outPath) {\n let rel = relative(dirname(options.outPath), options.sdkOptionsPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const jsonImport = sdkNeedsJson(root, includeInternal) ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${rel}';`);\n const valueImports: string[] = [];\n if (sdkNeedsBigIntReplacer(root, includeInternal)) valueImports.push('bigIntReplacer');\n if (sdkNeedsBigIntReviver(root, includeInternal)) valueImports.push('parseJson');\n if (sdkNeedsQueryString(root, includeInternal)) valueImports.push('buildQueryString');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${rel}';`);\n }\n } else {\n lines.push('');\n lines.push('export class SdkError extends Error {');\n lines.push(' constructor(');\n lines.push(' public readonly status: number,');\n lines.push(' public readonly statusText: string,');\n lines.push(' public readonly body: unknown,');\n lines.push(' public readonly headers: Headers,');\n lines.push(' ) {');\n lines.push(' super(`${status} ${statusText}`);');\n lines.push(\" this.name = 'SdkError';\");\n lines.push(' }');\n lines.push('}');\n lines.push('');\n lines.push('export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;');\n lines.push('');\n lines.push('export interface SdkOptions {');\n lines.push(' baseUrl: string;');\n lines.push(' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);');\n lines.push(' fetch?: SdkFetch;');\n lines.push(' /** Called once per request to produce a unique X-Request-ID header value */');\n lines.push(' requestIdFactory?: () => string;');\n lines.push('}');\n lines.push('');\n lines.push('export function createSdkFetch(options: SdkOptions): SdkFetch {');\n lines.push(' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());');\n lines.push(' return async (url: string, init: RequestInit): Promise<Response> => {');\n lines.push(\" const baseHeaders = typeof options.headers === 'function'\");\n lines.push(' ? await options.headers()');\n lines.push(' : options.headers ?? {};');\n lines.push(' const res = await fetch(`${options.baseUrl}${url}`, {');\n lines.push(' ...init,');\n lines.push(\" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\");\n lines.push(' });');\n lines.push(' if (!res.ok) {');\n lines.push(' const text = await res.text();');\n lines.push(' let body: unknown;');\n lines.push(' try { body = JSON.parse(text); } catch { body = text; }');\n lines.push(' throw new SdkError(res.status, res.statusText, body, res.headers);');\n lines.push(' }');\n lines.push(' return res;');\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push('export function buildQueryString(query: object | undefined): string {');\n lines.push(' const searchParams = new URLSearchParams();');\n lines.push(' if (query) {');\n lines.push(' for (const [k, v] of Object.entries(query)) {');\n lines.push(' if (v === undefined || v === null) continue;');\n lines.push(' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }');\n lines.push(' else searchParams.set(k, String(v));');\n lines.push(' }');\n lines.push(' }');\n lines.push(' const qs = searchParams.toString();');\n lines.push(\" return qs ? `?${qs}` : '';\");\n lines.push('}');\n lines.push('');\n lines.push('export async function parseJson<T>(res: Response): Promise<T> {');\n lines.push(' return JSON.parse(await res.text(), bigIntReviver) as T;');\n lines.push('}');\n }\n\n if (sdkNeedsJson(root, includeInternal) && !(options.sdkOptionsPath && options.outPath)) {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n\n lines.push('');\n\n // Client class\n lines.push('/**');\n const relFile = options.outPath ? relative(dirname(options.outPath), root.file) : root.file;\n lines.push(` * generated from [${basename(root.file)}](file://./${relFile})`);\n lines.push(' */');\n lines.push(`export class ${clientClassName} {`);\n lines.push(' constructor(private fetch: SdkFetch) {}');\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n lines.push('');\n if (mods.includes('deprecated')) lines.push(' /** @deprecated */');\n lines.push(...generateMethod(route, op, root.file, options));\n }\n }\n\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Render the method-block lines for an operation file as if they were declared inside a\n * client class. Returns one consolidated array of strings (each pre-indented for class body\n * level, with leading blank lines between methods) plus the set of method names emitted —\n * the caller uses the names to detect cross-file collisions when multiple files contribute\n * to the same area-level client.\n *\n * Skips operations marked `internal` unless `options.includeInternal` is set.\n */\nexport function generateClientMethods(\n root: OpRootNode,\n options: SdkCodegenOptions,\n): { lines: string[]; methodNames: string[] } {\n const lines: string[] = [];\n const methodNames: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n lines.push('');\n if (mods.includes('deprecated')) lines.push(' /** @deprecated */');\n lines.push(...generateMethod(route, op, root.file, options));\n methodNames.push(deriveMethodName(op, route));\n }\n }\n return { lines, methodNames };\n}\n\n// ─── Method generation ────────────────────────────────────────────────────\n\nfunction generateMethod(route: OpRouteNode, op: OpOperationNode, file: string, options: SdkCodegenOptions): string[] {\n const lines: string[] = [];\n const methodName = deriveMethodName(op, route);\n const httpMethod = op.method.toUpperCase();\n const { modelsWithInput, modelsWithOutput } = options;\n\n // Build method parameters (request-side — use Input variants)\n const params = buildMethodParams(route, op, modelsWithInput);\n const paramStr = params.map(p => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ');\n\n // Determine return type — response side uses Output variants (post-transform wire shape).\n // For non-JSON responses the schema is ignored: text/* is read as string, binary as Blob.\n const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];\n const isVoid = !primaryResponse?.bodyType;\n const respCategory = primaryResponse?.contentType ? classifyContentType(primaryResponse.contentType) : 'json';\n const dataType = isVoid\n ? 'void'\n : respCategory === 'text'\n ? 'string'\n : respCategory === 'binary'\n ? 'Blob'\n : renderOutputTsType(primaryResponse!.bodyType!, modelsWithOutput);\n const respHeaders = primaryResponse?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersShape = hasRespHeaders\n ? `{ ${respHeaders.map(h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput)}`).join('; ')} }`\n : '';\n const returnType = hasRespHeaders ? (isVoid ? `{ headers: ${headersShape} }` : `{ data: ${dataType}; headers: ${headersShape} }`) : dataType;\n\n // JSDoc\n const desc = op.description ?? route.description;\n if (op.name || desc) {\n const tags: string[] = [];\n if (op.name) tags.push(`@name ${op.name}`);\n if (desc) tags.push(`@description ${desc}`);\n if (tags.length === 1) {\n lines.push(` /** ${tags[0]} */`);\n } else {\n lines.push(` /**`);\n for (const tag of tags) lines.push(` * ${tag}`);\n lines.push(` */`);\n }\n }\n\n lines.push(` async ${methodName}(${paramStr}): Promise<${returnType}> {`);\n\n // Build URL with path params\n const urlExpr = buildUrlExpression(route.path, route.params);\n\n // Query string\n const hasQuery = !!op.query;\n let fetchUrl = urlExpr;\n if (hasQuery) {\n lines.push(` const qs = buildQueryString(query);`);\n fetchUrl = urlExpr;\n }\n\n // Build fetch options\n const strategy = classifyBodyStrategy(op);\n const hasBody = strategy.kind !== 'none';\n const hasOpHeaders = !!op.headers;\n\n // Pre-emit serialization preludes for multi-MIME strategies\n if (strategy.kind === 'multi-equal') {\n const defaultCt = strategy.bodies[0]!.contentType;\n lines.push(` const __contentType = options?.contentType ?? '${defaultCt}';`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n } else if (strategy.kind === 'multi-formdata-detect') {\n lines.push(` const __isFormData = body instanceof FormData;`);\n const nonMultipart = strategy.bodies.find(b => b.contentType !== 'multipart/form-data')!;\n lines.push(` const __contentType: string = __isFormData ? 'multipart/form-data' : '${nonMultipart.contentType}';`);\n lines.push(\n ` const __serialized: BodyInit = __isFormData ? (body as FormData) : ${jsonOrFormSerialize('body', nonMultipart.contentType)};`,\n );\n } else if (strategy.kind === 'multi-required-arg') {\n lines.push(` const __contentType = options.contentType;`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n }\n\n const fetchArgs: string[] = [];\n\n if (hasQuery) {\n fetchArgs.push(`url: \\`${fetchUrl}\\${qs}\\``);\n } else {\n fetchArgs.push(`url: \\`${fetchUrl}\\``);\n }\n\n fetchArgs.push(`method: '${httpMethod}'`);\n\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n // FormData supplies its own Content-Type with boundary; don't override it.\n fetchArgs.push('body: body');\n } else if (cat === 'urlencoded') {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: new URLSearchParams(body as unknown as Record<string, string>).toString()');\n } else if (cat === 'text' || cat === 'binary') {\n // text/* and binary mimes pass the body through to fetch as-is — no schema serialization.\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: body');\n } else {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: JSON.stringify(body, bigIntReplacer)');\n }\n } else if (hasBody) {\n // multi-equal | multi-formdata-detect | multi-required-arg — share a __contentType / __serialized prelude\n fetchArgs.push(`headers: { 'Content-Type': __contentType }`);\n fetchArgs.push('body: __serialized');\n }\n\n if (hasOpHeaders) {\n const lastHeaderIdx = fetchArgs.findIndex(a => a.startsWith('headers:'));\n if (lastHeaderIdx !== -1) {\n const existing = fetchArgs[lastHeaderIdx]!;\n const inner = existing.slice('headers: '.length).replace(/^\\{\\s*|\\s*\\}$/g, '');\n fetchArgs[lastHeaderIdx] = `headers: { ${inner}, ...customHeaders }`;\n } else {\n fetchArgs.push('headers: customHeaders');\n }\n }\n\n const resultPrefix = isVoid && !hasRespHeaders ? '' : 'const result = ';\n if (fetchArgs.length === 2 && !hasBody && !hasOpHeaders && !hasQuery) {\n // Simple case — inline\n lines.push(` ${resultPrefix}await this.fetch(\\`${fetchUrl}\\`, { method: '${httpMethod}' });`);\n } else {\n lines.push(` ${resultPrefix}await this.fetch(${fetchArgs[0]!.split(': ').slice(1).join(': ')}, {`);\n for (let i = 1; i < fetchArgs.length; i++) {\n lines.push(` ${fetchArgs[i]},`);\n }\n lines.push(` });`);\n }\n\n const readBodyExpr =\n respCategory === 'text' ? `await result.text()` : respCategory === 'binary' ? `await result.blob()` : `await parseJson<${dataType}>(result)`;\n\n if (hasRespHeaders) {\n const headerEntries = respHeaders\n .map(h => `${quoteKey(headerNameToProperty(h.name))}: result.headers.get('${h.name}') ?? undefined`)\n .join(', ');\n if (isVoid) {\n lines.push(` return { headers: { ${headerEntries} } };`);\n } else {\n lines.push(` const data = ${readBodyExpr};`);\n lines.push(` return { data, headers: { ${headerEntries} } };`);\n }\n } else if (!isVoid) {\n lines.push(` return ${readBodyExpr};`);\n }\n\n lines.push(' }');\n\n return lines;\n}\n\n// ─── URL building ─────────────────────────────────────────────────────────\n\nfunction buildUrlExpression(path: string, _?: ParamSource): string {\n // Replace {paramName} with ${encodeURIComponent(paramName)}\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, (_match, name) => {\n return `\\${encodeURIComponent(${name})}`;\n });\n}\n\n// ─── Method parameters ────────────────────────────────────────────────────\n\ninterface MethodParam {\n name: string;\n type: string;\n optional: boolean;\n}\n\nfunction buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {\n const params: MethodParam[] = [];\n\n // Path params — always first, always required (request-side — use Input variants)\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const p of route.params.nodes) {\n params.push({ name: p.name, type: renderInputTsType(p.type, modelsWithInput), optional: false });\n }\n } else if (route.params.kind === 'ref') {\n const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;\n params.push({ name: 'params', type: typeName, optional: false });\n } else {\n params.push({ name: 'params', type: renderInputTsType(route.params.node, modelsWithInput), optional: false });\n }\n }\n\n // Body (request-side — use Input variants)\n const strategy = classifyBodyStrategy(op);\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n params.push({ name: 'body', type: 'FormData', optional: false });\n } else if (cat === 'text') {\n params.push({ name: 'body', type: 'string', optional: false });\n } else if (cat === 'binary') {\n params.push({ name: 'body', type: 'Blob | ArrayBuffer | Uint8Array | string', optional: false });\n } else {\n params.push({ name: 'body', type: renderInputTsType(body.bodyType, modelsWithInput), optional: false });\n }\n } else if (strategy.kind === 'multi-equal') {\n const bodies = strategy.bodies;\n const bodyType = renderInputTsType(bodies[0]!.bodyType, modelsWithInput);\n params.push({ name: 'body', type: bodyType, optional: false });\n const ctUnion = bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType?: ${ctUnion} }`, optional: true });\n } else if (strategy.kind === 'multi-formdata-detect') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n } else if (strategy.kind === 'multi-required-arg') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n const ctUnion = strategy.bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType: ${ctUnion} }`, optional: false });\n }\n\n // Query (request-side — use Input variants)\n if (op.query) {\n if (op.query.kind === 'params') {\n const fields = op.query.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');\n params.push({ name: 'query', type: `{ ${fields} }`, optional: true });\n } else if (op.query.kind === 'ref') {\n const typeName = modelsWithInput?.has(op.query.name) ? `${op.query.name}Input` : op.query.name;\n params.push({ name: 'query', type: typeName, optional: true });\n } else {\n params.push({ name: 'query', type: renderInputTsType(op.query.node, modelsWithInput), optional: true });\n }\n }\n\n // Headers (request-side — use Input variants)\n if (op.headers) {\n if (op.headers.kind === 'params') {\n const fields = op.headers.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');\n params.push({ name: 'customHeaders', type: `{ ${fields} }`, optional: true });\n } else if (op.headers.kind === 'ref') {\n const typeName = modelsWithInput?.has(op.headers.name) ? `${op.headers.name}Input` : op.headers.name;\n params.push({ name: 'customHeaders', type: typeName, optional: true });\n } else {\n params.push({ name: 'customHeaders', type: renderInputTsType(op.headers.node, modelsWithInput), optional: true });\n }\n }\n\n return params;\n}\n\n// ─── Method name inference ────────────────────────────────────────────────\n\nfunction deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {\n if (op.sdk) return op.sdk;\n if (op.name) return nameToMethodName(op.name);\n return inferMethodName(op.method, route.path);\n}\n\nfunction nameToMethodName(name: string): string {\n const parts = name.split(/[\\s\\-_]+/).filter(Boolean);\n return parts.map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join('');\n}\n\nfunction inferMethodName(method: string, path: string): string {\n // Build a name from the path segments + method\n // e.g. GET /users/:id → getUsersById\n // e.g. POST /users → postUsers\n // e.g. DELETE /users/:id → deleteUsersById\n const segments = path.split('/').filter(s => s.length > 0);\n const parts: string[] = [method.toLowerCase()];\n\n for (const seg of segments) {\n if (seg.startsWith('{')) {\n // {id} → ById, {accountId} → ByAccountId\n const paramName = seg.slice(1, -1);\n parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));\n } else {\n // Regular segment — camelCase it\n const segParts = seg.split(/[.-]/).filter(Boolean);\n for (const sp of segParts) {\n parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));\n }\n }\n }\n\n return parts[0]! + parts.slice(1).join('');\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\nfunction deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\n/** Derive a client class name from a `.ck` file path, e.g. `users.ck` → `UsersClient`. Used for legacy flat (no-area) files. */\nexport function deriveClientClassName(file: string): string {\n return `${deriveBaseName(file)}Client`;\n}\n\n/** Camel-cased property name for a flat client on the SDK aggregator, e.g. `users.ck` → `users`. */\nexport function deriveClientPropertyName(file: string): string {\n const base = deriveBaseName(file);\n return base.charAt(0).toLowerCase() + base.slice(1);\n}\n\n/**\n * Pull `area` / `subarea` from a file's `root.meta` (set via `options { keys: { ... } }`).\n * Both are optional. `area` drives top-level SDK grouping; `subarea` drives nesting under\n * an area's client class.\n */\nexport function getAreaSubarea(root: OpRootNode): { area?: string; subarea?: string } {\n return { area: root.meta?.area, subarea: root.meta?.subarea };\n}\n\nfunction pascal(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction camel(value: string): string {\n const p = pascal(value);\n return p.charAt(0).toLowerCase() + p.slice(1);\n}\n\n/** Class name for the area-level client, e.g. `area=identity` → `IdentityClient`. */\nexport function deriveAreaClientClassName(area: string): string {\n return `${pascal(area)}Client`;\n}\n\n/** Property name on the SDK aggregator for an area, e.g. `area=identity` → `identity`. */\nexport function deriveAreaPropertyName(area: string): string {\n return camel(area);\n}\n\n/** Class name for a leaf subarea client, e.g. `(identity, invitations)` → `IdentityInvitationsClient`. */\nexport function deriveSubareaClientClassName(area: string, subarea: string): string {\n return `${pascal(area)}${pascal(subarea)}Client`;\n}\n\n/** Property name on the area client for a subarea, e.g. `subarea=invitations` → `invitations`. */\nexport function deriveSubareaPropertyName(subarea: string): string {\n return camel(subarea);\n}\n\n// ─── Type collection ──────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>, includeInternal = false): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n const publicOps = route.operations.filter(op => includeInternal || !resolveModifiers(route, op).includes('internal'));\n if (publicOps.length === 0) continue;\n // Only collect path-param types if there are public ops on this route\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of publicOps) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n if (resp.bodyType) {\n collectTypeNodeRefs(resp.bodyType, types);\n collectOutputTypeNodeRefs(resp.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectOutputTypeNodeRefs(m, out, modelsWithOutput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectInputTypeNodeRefs(param.type, out, modelsWithInput);\n }\n } else {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeNodeRefs(m, out, modelsWithInput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** True if any emitted operation has query params (drives the `buildQueryString` import). */\nfunction sdkNeedsQueryString(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')) continue;\n if (op.query) return true;\n }\n }\n return false;\n}\n\n/** True if any emitted operation serializes a JSON request body (uses bigIntReplacer). */\nfunction sdkNeedsBigIntReplacer(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')) continue;\n if (op.request && op.request.bodies.some(b => isJsonMime(b.contentType))) return true;\n }\n }\n return false;\n}\n\n/** True if any public operation parses a JSON response body (uses bigIntReviver). */\nfunction sdkNeedsBigIntReviver(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')) continue;\n if (\n op.responses.some(r => {\n if (!r.bodyType) return false;\n // Only JSON-shaped responses use parseJson — text/binary read raw.\n return !r.contentType || classifyContentType(r.contentType) === 'json';\n })\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction sdkNeedsJson(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')) continue;\n const check = (src: ParamSource | undefined) => {\n if (!src || src.kind === 'ref') return false;\n if (src.kind === 'params') return src.nodes.some(p => typeNeedsScalar(p.type, 'json'));\n return typeNeedsScalar(src.node, 'json');\n };\n if (\n !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, 'json')) ||\n op.responses.some(r => r.bodyType && typeNeedsScalar(r.bodyType, 'json')) ||\n check(op.query) ||\n check(op.headers) ||\n check(route.params)\n )\n return true;\n }\n }\n return false;\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\n// ─── Type import resolution ───────────────────────────────────────────────\n\nfunction generateTypeImports(types: string[], opFile: string, options: SdkCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import type { ${names.sort().join(', ')} } from '${rel}';`);\n }\n\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import type { ${type} } from './${moduleName}.js';`);\n }\n } else {\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import type { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n\n// ─── Shared SDK files ──────────────────────────────────────────────────────\n\n/** Generate the shared SdkOptions interface file. */\nexport function generateSdkOptions(): string {\n return [\n 'export class SdkError extends Error {',\n ' constructor(',\n ' public readonly status: number,',\n ' public readonly statusText: string,',\n ' public readonly body: unknown,',\n ' public readonly headers: Headers,',\n ' ) {',\n ' super(`${status} ${statusText}`);',\n \" this.name = 'SdkError';\",\n ' }',\n '}',\n '',\n 'export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;',\n '',\n 'export interface SdkOptions {',\n ' baseUrl: string;',\n ' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);',\n ' fetch?: SdkFetch;',\n ' /** Called once per request to produce a unique X-Request-ID header value */',\n ' requestIdFactory?: () => string;',\n '}',\n '',\n 'export const bigIntReplacer = (_: string, value: any): any => {',\n \" if (typeof value === 'bigint') {\",\n \" return value.toString() + 'n';\",\n ' }',\n ' return value;',\n '};',\n '',\n 'export const bigIntReviver = (_: string, value: any): any => {',\n \" if (typeof value === 'string' && /^-?\\\\d+n$/.test(value)) {\",\n ' return BigInt(value.slice(0, -1));',\n ' }',\n ' return value;',\n '};',\n '',\n JSON_VALUE_TYPE_DECL,\n '',\n 'export function createSdkFetch(options: SdkOptions): SdkFetch {',\n ' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());',\n ' return async (url: string, init: RequestInit): Promise<Response> => {',\n \" const baseHeaders = typeof options.headers === 'function'\",\n ' ? await options.headers()',\n ' : options.headers ?? {};',\n ' const res = await fetch(`${options.baseUrl}${url}`, {',\n ' ...init,',\n \" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\",\n ' });',\n ' if (!res.ok) {',\n ' const text = await res.text();',\n ' let body: unknown;',\n ' try { body = JSON.parse(text); } catch { body = text; }',\n ' throw new SdkError(res.status, res.statusText, body, res.headers);',\n ' }',\n ' return res;',\n ' };',\n '}',\n '',\n 'export function buildQueryString(query: object | undefined): string {',\n ' const searchParams = new URLSearchParams();',\n ' if (query) {',\n ' for (const [k, v] of Object.entries(query)) {',\n ' if (v === undefined || v === null) continue;',\n ' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }',\n ' else searchParams.set(k, String(v));',\n ' }',\n ' }',\n ' const qs = searchParams.toString();',\n \" return qs ? `?${qs}` : '';\",\n '}',\n '',\n 'export async function parseJson<T>(res: Response): Promise<T> {',\n ' return JSON.parse(await res.text(), bigIntReviver) as T;',\n '}',\n '',\n ].join('\\n');\n}\n\n/**\n * Reference to a per-file leaf client emitted to its own `*.client.ts`. Used by the\n * aggregator to import the class and wire it as either a top-level `sdk.<prop>` or a\n * nested `sdk.<area>.<subarea>` property.\n */\nexport interface SdkClientInfo {\n /** Client class name (e.g. `UsersClient`, `IdentityInvitationsClient`). */\n className: string;\n /** Property name to expose this client under (e.g. `users`, `invitations`). */\n propertyName: string;\n /** Module specifier for the leaf file, relative to `sdk.ts` and `.js`-suffixed. */\n importPath: string;\n}\n\n/**\n * One area-level (no-subarea) `.ck` file whose methods are merged into the area's\n * `<Area>Client` (emitted to its own `<area>.client.ts`).\n */\nexport interface SdkAreaInlineFile {\n /** Parsed AST. */\n root: OpRootNode;\n /** Codegen options for this file (must have `outPath` pointing at the area client file so type-import paths resolve correctly). */\n codegenOptions: SdkCodegenOptions;\n}\n\n/** A grouping of files that share the same `keys.area`. */\nexport interface SdkAreaInfo {\n area: string;\n /**\n * Reference to the `<Area>Client` class — the file that holds it lives at\n * `client.importPath` (relative to `sdk.ts`) and is generated separately by\n * {@link generateAreaClient}. The aggregator just imports it.\n */\n client: SdkClientInfo;\n}\n\nexport interface SdkAggregatorInput {\n /** Files with no `keys.area` — kept as flat `Sdk.<filename>` properties (legacy behavior). */\n topLevelClients: SdkClientInfo[];\n /** One entry per `keys.area`. */\n areas: SdkAreaInfo[];\n /** Path to `sdk-options.ts` to import `SdkOptions`/`createSdkFetch`/etc. from. */\n sdkOptionsImportPath?: string;\n /** Name of the top-level aggregator class. Defaults to `Sdk`. */\n sdkClassName?: string;\n}\n\n/** Inputs to {@link generateAreaClient}. */\nexport interface AreaClientInput {\n /** Area name (e.g. `payments`). Drives the generated class name (`PaymentsClient`). */\n area: string;\n /** Output path of the generated `<area>.client.ts` file. Used to resolve relative type / leaf-client / sdk-options imports. */\n outPath: string;\n /** Files contributing inlined methods to the area client (typically area-level files with no subarea). */\n inlineFiles: SdkAreaInlineFile[];\n /** Subarea leaf clients exposed as named properties on the area client. */\n subareaClients: { propertyName: string; client: SdkClientInfo }[];\n /** Path to `sdk-options.ts`, used for `SdkFetch` and runtime helpers. */\n sdkOptionsPath: string;\n}\n\n/**\n * Generate a complete `<area>.client.ts` file: the `<Area>Client` class with\n * subarea property fields, a constructor that wires them, and inlined methods\n * merged from every area-level file in `inlineFiles`.\n *\n * Emitted by the plugin alongside the per-leaf `*.client.ts` files. The SDK\n * aggregator just imports the resulting class — see {@link generateSdkAggregator}.\n *\n * @throws if two area-level files contribute the same method name to the area —\n * disambiguate via `sdk:` on the operation, or move one into a subarea.\n */\nexport function generateAreaClient(input: AreaClientInput): string {\n const { area, outPath, inlineFiles, subareaClients, sdkOptionsPath } = input;\n const className = deriveAreaClientClassName(area);\n\n // ── Merge inputs across all inline files ────────────────────────────────\n const collectedMethodLines: string[] = [];\n const seenMethods = new Set<string>();\n const typesByImportPath = new Map<string, Set<string>>();\n const unresolvedTypes = new Set<string>();\n let needsJson = false;\n let needsBigIntReplacer = false;\n let needsBigIntReviver = false;\n let needsQueryString = false;\n\n for (const inline of inlineFiles) {\n const includeInternal = inline.codegenOptions.includeInternal ?? false;\n const { lines: methodLines, methodNames } = generateClientMethods(inline.root, inline.codegenOptions);\n for (const name of methodNames) {\n if (seenMethods.has(name)) {\n throw new Error(\n `[sdk] duplicate method '${name}' in area '${area}': two area-level files contribute the same method. Disambiguate via 'sdk:' or move one into a subarea.`,\n );\n }\n seenMethods.add(name);\n }\n collectedMethodLines.push(...methodLines);\n if (sdkNeedsJson(inline.root, includeInternal)) needsJson = true;\n if (sdkNeedsBigIntReplacer(inline.root, includeInternal)) needsBigIntReplacer = true;\n if (sdkNeedsBigIntReviver(inline.root, includeInternal)) needsBigIntReviver = true;\n if (sdkNeedsQueryString(inline.root, includeInternal)) needsQueryString = true;\n\n // Resolve each file's type refs against THIS file's modelOutPaths, but\n // produce import paths relative to the area client's outPath (not the\n // contributing file's outPath, which pointed at the now-defunct sdk.ts).\n const typesForFile = collectTypes(\n inline.root,\n inline.codegenOptions.modelsWithInput,\n inline.codegenOptions.modelsWithOutput,\n includeInternal,\n );\n const { modelOutPaths } = inline.codegenOptions;\n if (modelOutPaths) {\n const fromDir = dirname(outPath);\n for (const t of typesForFile) {\n const typeOutPath = modelOutPaths.get(t);\n if (typeOutPath) {\n let rel = relative(fromDir, typeOutPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const set = typesByImportPath.get(rel) ?? new Set();\n set.add(t);\n typesByImportPath.set(rel, set);\n } else {\n unresolvedTypes.add(t);\n }\n }\n }\n }\n\n // ── Imports ─────────────────────────────────────────────────────────────\n let sdkOptionsRel = relative(dirname(outPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!sdkOptionsRel.startsWith('.')) sdkOptionsRel = './' + sdkOptionsRel;\n\n const lines: string[] = [];\n const jsonImport = needsJson ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${sdkOptionsRel}';`);\n const valueImports: string[] = [];\n if (needsBigIntReplacer) valueImports.push('bigIntReplacer');\n if (needsBigIntReviver) valueImports.push('parseJson');\n if (needsQueryString) valueImports.push('buildQueryString');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${sdkOptionsRel}';`);\n }\n\n for (const path of [...typesByImportPath.keys()].sort()) {\n const names = [...typesByImportPath.get(path)!].sort();\n lines.push(`import type { ${names.join(', ')} } from '${path}';`);\n }\n for (const t of [...unresolvedTypes].sort()) {\n lines.push(`import type { ${t} } from './${pascalToDotCase(t)}.js';`);\n }\n\n // Leaf client imports (subareas only — top-level clients live next to sdk.ts).\n const importedClients = new Set<string>();\n for (const sc of subareaClients) {\n const key = `${sc.client.className}|${sc.client.importPath}`;\n if (importedClients.has(key)) continue;\n importedClients.add(key);\n lines.push(`import { ${sc.client.className} } from '${sc.client.importPath}';`);\n }\n lines.push('');\n\n // ── <Area>Client class ──────────────────────────────────────────────────\n lines.push(`export class ${className} {`);\n for (const sc of subareaClients) {\n lines.push(` readonly ${sc.propertyName}: ${sc.client.className};`);\n }\n if (subareaClients.length > 0) lines.push('');\n if (collectedMethodLines.length > 0 || subareaClients.length > 0) {\n const fetchModifier = collectedMethodLines.length > 0 ? 'private ' : '';\n lines.push(` constructor(${fetchModifier}fetch: SdkFetch) {`);\n for (const sc of subareaClients) {\n lines.push(` this.${sc.propertyName} = new ${sc.client.className}(fetch);`);\n }\n lines.push(' }');\n }\n for (const ln of collectedMethodLines) lines.push(ln);\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the SDK aggregator (`sdk.ts`) — the entry-point file consumers import.\n *\n * Imports every `<Area>Client` (one per area, generated by {@link generateAreaClient}\n * to its own `<area>.client.ts`) and every leaf top-level client, then emits a\n * `class Sdk` that exposes them as properties.\n */\nexport function generateSdkAggregator(input: SdkAggregatorInput): string {\n const sdkOptionsImportPath = input.sdkOptionsImportPath ?? './sdk-options.js';\n const sdkClassName = input.sdkClassName ?? 'Sdk';\n\n const lines: string[] = [];\n lines.push(`import type { SdkOptions } from '${sdkOptionsImportPath}';`);\n lines.push(`import { createSdkFetch } from '${sdkOptionsImportPath}';`);\n\n const importedClients = new Set<string>();\n const pushClientImport = (c: SdkClientInfo): void => {\n const key = `${c.className}|${c.importPath}`;\n if (importedClients.has(key)) return;\n importedClients.add(key);\n lines.push(`import { ${c.className} } from '${c.importPath}';`);\n };\n // Areas first, then top-level — keeps the aggregator's import order stable.\n for (const area of input.areas) pushClientImport(area.client);\n for (const c of input.topLevelClients) pushClientImport(c);\n lines.push('');\n\n lines.push(`export class ${sdkClassName} {`);\n for (const area of input.areas) {\n lines.push(` readonly ${deriveAreaPropertyName(area.area)}: ${area.client.className};`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` readonly ${c.propertyName}: ${c.className};`);\n }\n lines.push('');\n lines.push(' constructor(options: SdkOptions) {');\n lines.push(' const sdkFetch = options.fetch ?? createSdkFetch(options);');\n for (const area of input.areas) {\n lines.push(` this.${deriveAreaPropertyName(area.area)} = new ${area.client.className}(sdkFetch);`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` this.${c.propertyName} = new ${c.className}(sdkFetch);`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n","import { relative, dirname } from 'node:path';\nimport type { ContractRootNode, ModelNode, FieldNode } from '@contractkit/core';\nimport { computeModelsWithOutput, collectExternalOutputRefs } from '@contractkit/core';\nimport type { ContractCodegenContext } from './codegen-contract.js';\nimport {\n collectExternalRefs,\n collectExternalInputRefs,\n computeModelsWithInput,\n topoSortModels,\n resolveImportPath,\n rootNeedsScalar,\n} from './codegen-contract.js';\nimport { renderTsType, renderInputTsType, renderOutputTsType, quoteKey, JSON_VALUE_TYPE_DECL } from './ts-render.js';\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Generate plain TypeScript interfaces/types from a contract AST.\n * Unlike `generateContract()` which produces Zod schemas, this emits\n * vanilla TypeScript `interface` and `type` declarations suitable\n * for SDK consumers that don't need runtime validation.\n */\nexport function generatePlainTypes(root: ContractRootNode, context?: ContractCodegenContext): string {\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = computeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input/Output refs needed for variant fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? collectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n // Type-only imports for external references\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n lines.push(`import type { ${ref} } from '${importPath}';`);\n }\n if (allExternalRefs.length > 0) lines.push('');\n\n if (rootNeedsScalar(root, 'json')) {\n if (context?.jsonValueImportPath) {\n lines.push(`import type { JsonValue } from '${context.jsonValueImportPath}';`);\n } else {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n lines.push('');\n }\n\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n for (const model of topoSortModels(root.models)) {\n lines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, allModelsWithOutput, modelMap));\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\nfunction generateModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithOutput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);\n }\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = model.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(model.name) ?? false);\n\n const lines = needsInputSplit ? generateVisibilityModel(model, outPath, modelsWithInput, modelMap) : generateSimpleModel(model, outPath, modelMap);\n\n if (modelsWithOutput?.has(model.name)) {\n lines.push('');\n lines.push(...generateOutputModel(model, modelsWithOutput));\n }\n return lines;\n}\n\n/** Recursively collect every field name defined on `bases` and their ancestors. Used to detect\n * fields that the child re-declares without an explicit `override` keyword — those still need an\n * `Omit<Base, …>` wrap, otherwise the child's narrower/incompatible declaration collides with the\n * inherited one. */\nfunction collectInheritedFieldNames(bases: string[], modelMap: Map<string, ModelNode>): Set<string> {\n const result = new Set<string>();\n const visit = (name: string): void => {\n const m = modelMap.get(name);\n if (!m || m.type) return;\n for (const f of m.fields) result.add(f.name);\n for (const b of m.bases ?? []) visit(b);\n };\n for (const b of bases) visit(b);\n return result;\n}\n\n/** Names of fields the child declaration overrides — explicit `override` plus any field whose\n * name shadows an inherited one. The latter catches single-base redeclarations that omit the\n * `override` keyword (e.g. narrowing `kind: BusinessRoleKind` → `kind: 'employee'`). */\nfunction computeOverrideNames(model: ModelNode, modelMap?: Map<string, ModelNode>): string[] {\n const inherited = modelMap ? collectInheritedFieldNames(model.bases ?? [], modelMap) : new Set<string>();\n return model.fields.filter(f => f.override || inherited.has(f.name)).map(f => f.name);\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n lines.push(` * ${model.description}`);\n }\n\n const relPath = outPath ? relative(dirname(outPath), model.loc.file) : model.loc.file;\n lines.push(` * generated from [${model.name}](file://./${relPath}#L${model.loc.line})`);\n lines.push(' */');\n return lines;\n}\n\nfunction generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export type ${model.name} = ${renderTsType(model.type!)};`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export type ${model.name}Input = ${renderInputTsType(model.type!, modelsWithInput)};`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = ${renderOutputTsType(model.type!, modelsWithOutput)};`);\n }\n return lines;\n}\n\n/** Build the `extends` clause for a model.\n * Each entry in `overrideNames` is wrapped in `Omit<Base, 'name1' | 'name2'>` per base so the\n * subclass can legally redeclare those fields with new (possibly incompatible) types.\n * TypeScript's `Omit<T, K extends keyof any>` tolerates omit keys that don't appear on the base,\n * so we apply the same omit list to every base without per-base field-set lookup. */\nfunction buildExtendsClause(bases: string[], overrideNames: string[], baseNameResolver: (b: string) => string): string {\n if (bases.length === 0) return '';\n if (overrideNames.length === 0) return ` extends ${bases.map(baseNameResolver).join(', ')}`;\n const omitKeys = overrideNames.map(n => `'${n}'`).join(' | ');\n const wrapped = bases.map(b => `Omit<${baseNameResolver(b)}, ${omitKeys}>`);\n return ` extends ${wrapped.join(', ')}`;\n}\n\nfunction generateSimpleModel(model: ModelNode, outPath?: string, modelMap?: Map<string, ModelNode>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n\n for (const field of model.fields) {\n lines.push(` ${renderField(field)}`);\n }\n\n lines.push('}');\n return lines;\n}\n\nfunction generateVisibilityModel(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelMap?: Map<string, ModelNode>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n\n // Read type — omit writeonly fields\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n for (const field of readFields) {\n lines.push(` ${renderField(field)}`);\n }\n lines.push('}');\n lines.push('');\n\n // Write type — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read type\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n const inputResolver = (b: string) => (modelsWithInput?.has(b) ? `${b}Input` : b);\n lines.push(`export interface ${model.name}Input${buildExtendsClause(bases, overrideNames, inputResolver)} {`);\n for (const field of writeFields) {\n lines.push(` ${modelsWithInput ? renderInputField(field, modelsWithInput) : renderField(field)}`);\n }\n lines.push('}');\n\n return lines;\n}\n\n// ─── Field rendering ──────────────────────────────────────────────────────\n\nfunction renderField(field: FieldNode): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderTsType(field.type);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n if (jsdocParts.length > 0) {\n return `/** ${jsdocParts.join(' ')} */\\n ${line}`;\n }\n return line;\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderInputTsType(field.type, modelsWithInput);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n if (jsdocParts.length > 0) {\n return `/** ${jsdocParts.join(' ')} */\\n ${line}`;\n }\n return line;\n}\n\n// ─── Output (post-transform wire shape) ──────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyOutputCase(name: string, c: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!c || c === 'camel') return name;\n if (c === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\n/**\n * Emit `${name}Output` for a model in the output transitive set.\n * - Direct hits (model.outputCase set): rename keys per the transform and substitute nested refs.\n * - Transitive hits: keep field names as-is but substitute nested refs with their Output variants.\n *\n * `extends` is dropped for direct-hit models because the Zod schema flattens fields when an\n * ancestor has format(...) (see `flattenFormatChain` in codegen-contract); we mirror that here\n * so the plain interface matches the wire shape produced by the Zod transform.\n */\nfunction generateOutputModel(model: ModelNode, modelsWithOutput: Set<string>): string[] {\n const lines: string[] = [];\n const outputCase = model.outputCase && model.outputCase !== 'camel' ? model.outputCase : undefined;\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n\n // Transitive-only (no direct outputCase): preserve `extends` and original key names.\n if (!outputCase) {\n const baseExt =\n model.bases?.[0] && modelsWithOutput.has(model.bases?.[0])\n ? ` extends ${model.bases?.[0]}Output`\n : model.bases?.[0]\n ? ` extends ${model.bases?.[0]}`\n : '';\n lines.push(`export interface ${model.name}Output${baseExt} {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, model.outputCase, modelsWithOutput)}`);\n }\n lines.push('}');\n return lines;\n }\n\n // Direct hit: emit a flat interface with renamed keys.\n lines.push(`export interface ${model.name}Output {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, outputCase, modelsWithOutput)}`);\n }\n lines.push('}');\n return lines;\n}\n\nfunction renderOutputField(field: FieldNode, outputCase: 'camel' | 'snake' | 'pascal' | undefined, modelsWithOutput: Set<string>): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n const key = applyOutputCase(field.name, outputCase);\n let typeStr = renderOutputTsType(field.type, modelsWithOutput);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(key)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n if (jsdocParts.length > 0) {\n return `/** ${jsdocParts.join(' ')} */\\n ${line}`;\n }\n return line;\n}\n","import { resolve, join, relative, dirname } from 'node:path';\nimport type { ContractRootNode, OpRootNode } from '@contractkit/core';\nimport { collectTypeRefs, collectPublicTypeNames } from '@contractkit/core';\n\nexport const TEMPLATE_VAR_RE = /\\{\\w+\\}/;\n\nexport function resolveTemplate(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{(\\w+)\\}/g, (_, key) => vars[key] ?? `{${key}}`);\n}\n\nexport function includesFilename(p: string): boolean {\n const last = p.split('/').pop() ?? '';\n return last.includes('.');\n}\n\nexport function commonDir(files: string[], rootDir: string): string {\n if (files.length === 0) return resolve(rootDir);\n const parts = files.map(f => dirname(f).split('/'));\n const first = parts[0]!;\n let depth = first.length;\n for (const p of parts) {\n for (let i = 0; i < depth; i++) {\n if (p[i] !== first[i]) {\n depth = i;\n break;\n }\n }\n }\n return first.slice(0, depth).join('/') || '/';\n}\n\n// ─── Server / Zod output paths ─────────────────────────────────────────────\n\nexport function computeOpOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n const baseName = filePath.split('/').pop()!;\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n const defaultName = `${filename}${defaultSuffix}`;\n const baseOutDir = resolve(baseDir);\n\n if (output && TEMPLATE_VAR_RE.test(output)) {\n const resolved = resolveTemplate(output, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return join(baseOutDir, resolved);\n return join(baseOutDir, resolved, defaultName);\n }\n if (output) {\n if (includesFilename(output)) return join(baseOutDir, output);\n return join(baseOutDir, output, relDir, defaultName);\n }\n return join(baseOutDir, relDir, defaultName);\n}\n\nexport function computeContractOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n return computeOpOutPath(filePath, baseDir, output, defaultSuffix, commonRoot, meta);\n}\n\n// ─── SDK output paths ──────────────────────────────────────────────────────\n\nexport function computeSdkOutPath(\n filePath: string,\n rootDir: string,\n clientOutput: string | undefined,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.client.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return join(baseOutDir, resolved);\n return join(baseOutDir, resolved, defaultOutName);\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return join(baseOutDir, clientOutput);\n return join(baseOutDir, clientOutput, relDir, defaultOutName);\n }\n return join(baseOutDir, relDir, defaultOutName);\n}\n\n/**\n * Resolve the output path for a synthesized `<area>.client.ts` — the file holding the\n * `<Area>Client` class that aggregates an area's inlined methods and subarea wiring.\n *\n * Uses the same `output.clients` template as leaf clients, with `{filename}` and `{area}`\n * substituted to the area name and `{subarea}` substituted to the empty string. Resulting\n * double-slashes from the empty substitution are collapsed, and a final segment that\n * would otherwise begin with a dot (e.g. `.client.ts` from `{subarea}.client.ts`) is\n * prefixed with the area so the file isn't hidden.\n */\nexport function computeSdkAreaClientOutPath(area: string, rootDir: string, clientOutput: string | undefined): string {\n const filename = area;\n const baseOutDir = resolve(rootDir);\n const fixHiddenSegment = (path: string): string => {\n const segments = path.split('/');\n const last = segments[segments.length - 1] ?? '';\n if (last.startsWith('.')) segments[segments.length - 1] = `${filename}${last}`;\n return segments.join('/');\n };\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: '', ext: 'ck', area, subarea: '' });\n const cleaned = fixHiddenSegment(resolved.replace(/\\/+/g, '/').replace(/^\\//, ''));\n if (includesFilename(cleaned)) return join(baseOutDir, cleaned);\n return join(baseOutDir, cleaned, `${filename}.client.ts`);\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return join(baseOutDir, clientOutput);\n return join(baseOutDir, clientOutput, `${filename}.client.ts`);\n }\n return join(baseOutDir, `${filename}.client.ts`);\n}\n\nexport function computeSdkTypeOutPath(\n filePath: string,\n rootDir: string,\n typeOutput: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (TEMPLATE_VAR_RE.test(typeOutput)) {\n const resolved = resolveTemplate(typeOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return join(baseOutDir, resolved);\n return join(baseOutDir, resolved, defaultOutName);\n }\n if (includesFilename(typeOutput)) return join(baseOutDir, typeOutput);\n return join(baseOutDir, typeOutput, relDir, defaultOutName);\n}\n\nexport function generateBarrelFiles(contractPaths: string[]): { outPath: string; content: string }[] {\n const byDir = new Map<string, string[]>();\n for (const outPath of contractPaths) {\n const dir = dirname(outPath);\n const group = byDir.get(dir) ?? [];\n group.push(outPath);\n byDir.set(dir, group);\n }\n const results: { outPath: string; content: string }[] = [];\n for (const [dir, files] of byDir) {\n const exports = files\n .map(f => `export * from './${f.split('/').pop()!.replace(/\\.ts$/, '.js')}';`)\n .sort()\n .join('\\n');\n results.push({ outPath: join(dir, 'index.ts'), content: `// Auto-generated barrel file\\n${exports}\\n` });\n }\n return results;\n}\n\nexport function computePubliclyReachableTypes(\n opAsts: OpRootNode[],\n contractAsts: ContractRootNode[],\n modelsWithInput: Set<string>,\n modelsWithOutput: Set<string> = new Set(),\n): Set<string> | null {\n if (opAsts.length === 0) return null;\n const reachable = new Set<string>();\n for (const opAst of opAsts) {\n for (const name of collectPublicTypeNames(opAst, modelsWithInput, modelsWithOutput)) reachable.add(name);\n }\n const modelDeps = new Map<string, Set<string>>();\n for (const contractAst of contractAsts) {\n for (const model of contractAst.models) {\n const deps = new Set<string>();\n if (model.bases) for (const b of model.bases) deps.add(b);\n if (model.type) collectTypeRefs(model.type, deps);\n for (const field of model.fields) collectTypeRefs(field.type, deps);\n modelDeps.set(model.name, deps);\n }\n }\n const frontier = [...reachable];\n while (frontier.length > 0) {\n const name = frontier.pop()!;\n const baseName = name.endsWith('Input') ? name.slice(0, -5) : name.endsWith('Output') ? name.slice(0, -6) : name;\n for (const dep of modelDeps.get(baseName) ?? []) {\n if (!reachable.has(dep)) {\n reachable.add(dep);\n frontier.push(dep);\n }\n if (modelsWithInput.has(dep)) {\n const inputDep = `${dep}Input`;\n if (!reachable.has(inputDep)) {\n reachable.add(inputDep);\n frontier.push(inputDep);\n }\n }\n if (modelsWithOutput.has(dep)) {\n const outputDep = `${dep}Output`;\n if (!reachable.has(outputDep)) {\n reachable.add(outputDep);\n frontier.push(outputDep);\n }\n }\n }\n }\n return reachable;\n}\n"],"mappings":";;;;AAAA,SAASA,WAAAA,UAASC,QAAAA,OAAMC,YAAAA,WAAUC,WAAAA,UAASC,YAAAA,iBAAgB;AAC3D,SAAS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cAAsB6B,UAA6B;AACtE,MAAI;AACA6L,cAAU1F,SAAQhI,YAAAA,GAAe;MAAE2N,WAAW;IAAK,CAAA;AACnDC,kBAAc5N,cAAc6N,6BAA6BhM,QAAAA,GAAW,OAAA;EACxE,QAAQ;EAER;AACJ;AAPSD;AAST,SAASN,iBAAiBwM,UAAkB;AACxC,MAAIA,SAASrD,WAAW,EAAG;AAC3B,QAAMsD,cAAc,oBAAIzH,IAAAA;AACxB,aAAW0H,OAAOF,UAAU;AACxB,QAAIzM,WAAW2M,GAAAA,GAAM;AACjBC,aAAOD,KAAK;QAAEE,OAAO;MAAK,CAAA;AAC1BH,kBAAYvB,IAAIxE,SAAQgG,GAAAA,CAAAA;IAC5B;EACJ;AAEA,aAAWG,OAAOJ,aAAa;AAC3B,QAAIK,UAAUD;AACd,WAAOC,QAAQ3D,SAAS,GAAG;AACvB,UAAI;AACA,YAAI4D,YAAYD,OAAAA,EAAS3D,WAAW,GAAG;AACnC6D,oBAAUF,OAAAA;AACVA,oBAAUpG,SAAQoG,OAAAA;QACtB,OAAO;AACH;QACJ;MACJ,QAAQ;AACJ;MACJ;IACJ;EACJ;AACJ;AAzBS9M;AA4BT,SAASwE,gBAAgBnG,QAAe;AACpC,SAAO4O,KAAKC,UAAU7O,UAAU,IAAA;AACpC;AAFSmG;","names":["resolve","join","relative","dirname","basename","existsSync","readFileSync","writeFileSync","mkdirSync","rmSync","readdirSync","rmdirSync","relative","dirname","collectTypeRefs","computeModelsWithOutput","ckComputeModelsWithOutput","collectExternalOutputRefs","ckCollectExternalOutputRefs","modeToWrapper","mode","computeModelsWithInput","models","externalModelsWithInput","Set","result","model","fields","some","f","visibility","add","name","changed","has","refs","field","collectTypeRefs","type","bases","b","ref","generateComments","outPath","lines","push","deprecated","description","relPath","relative","dirname","loc","file","line","generateContract","root","context","needsDateTime","rootNeedsDateTime","needsDuration","rootNeedsScalar","needsInterval","needsBinary","needsDatetime","needsJson","externalRefs","collectExternalRefs","modelsWithInput","localModelsWithInput","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","ckComputeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","ckCollectExternalOutputRefs","allExternalRefs","sort","luxonImports","length","join","importPath","resolveImportPath","modelsWithWriteonly","filter","m","map","modelMap","Map","topoSortModels","generateModel","currentOutPath","flattenFormatChain","firstBase","parent","get","flatParent","parentHasFormat","inputCase","undefined","outputCase","merged","set","values","generateTypeAlias","effective","needsInputSplit","generateThreeSchemaModel","generateSimpleModel","renderType","renderInputType","wrapper","hasInputTransform","hasOutputTransform","inputBody","renderFieldsAsSnakeCase","renderFieldsAsPascalCase","renderFields","l","inputKey","applyCase","outputKey","val","optional","quoteKey","typeSource","body","head","tail","slice","buildExtendChain","resolveName","collectEffectiveWritableFieldNames","modelName","base","delete","allFields","hasWriteonly","baseBody","readFields","readBody","writeFields","writeBody","renderInputFields","fieldsToOmit","omitClause","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","caseTransform","defaultMode","flatMap","renderField","pascalKey","expr","default","nullable","dv","escapeString","String","snakeKey","parseCaseTransform","kind","renderScalar","renderArray","renderTuple","renderRecord","renderEnum","renderLiteral","renderUnion","renderDiscriminatedUnion","renderIntersection","inner","renderInlineObject","renderRegexLiteral","source","regexHasAnchor","startsWith","endsWith","i","backslashes","e","min","max","len","regex","fmt","format","validParts","validation","message","a","item","t","items","r","key","value","vals","v","u","members","discriminator","first","rest","every","member","fieldLines","o","snakeLines","joined","transformEntries","pascalLines","renderInputScalar","renderInputField","renderQueryType","renderQueryField","isValidIdentifier","test","typeNeedsDateTime","typeNeedsScalar","localNames","collectInputTypeRefs","out","forEach","deps","localDeps","inDegree","d","dep","remaining","queue","sorted","shift","other","rem","includes","refName","refOutPath","modelOutPaths","fromDir","rel","moduleName","pascalToDotCase","resolveModifiers","resolveSecurity","SECURITY_NONE","classifyContentType","JSON_VALUE_TYPE_DECL","quoteKey","name","test","headerNameToProperty","parts","split","filter","Boolean","map","p","i","lower","toLowerCase","charAt","toUpperCase","slice","join","renderTsType","type","kind","renderTsScalar","inner","item","needsParens","items","key","value","values","v","String","members","renderTsInlineObject","fields","entries","f","opt","optional","renderInputTsType","modelsWithInput","size","has","m","renderOutputTsType","modelsWithOutput","basename","dirname","relative","bodyParserToken","contentType","classifyContentType","bodyTypesStructurallyEqual","a","b","kind","bb","name","min","max","len","regex","format","item","items","length","every","x","i","key","value","values","v","members","m","discriminator","lazy","inner","mode","fields","f","g","optional","nullable","visibility","default","deprecated","type","generateOp","root","options","types","collectTypes","modelsWithInput","modelsWithOutput","services","collectServices","routerName","deriveRouterName","file","needsParseAndValidate","routeNeedsValidation","body","needsSignature","fileNeedsSignature","needsSecurity","fileNeedsSecurity","koaImports","push","join","svc","modulePath","meta","deriveModulePath","servicePathTemplate","generateTypeImports","opNeedsDateTime","helpers","opNeedsScalar","lines","relFile","outPath","relative","dirname","basename","includeInternal","route","routes","op","operations","resolveModifiers","includes","generateHandler","allContent","needsZod","test","desc","description","loc","line","effectiveSecurity","resolveSecurity","SECURITY_NONE","mods","method","path","replace","bodies","request","hasBody","isSingleMultipart","middlewares","args","requireMfa","undefined","parserTokens","Array","from","Set","map","tokensExpr","t","signature","middlewareStr","generateParamValidation","params","paramsMode","query","queryMode","headers","headersMode","renderInputType","bodyType","annotation","primaryResponse","responses","find","r","serviceParts","inferService","respHeaders","hasRespHeaders","headersAnnotation","h","quoteKey","headerNameToProperty","renderOutputTsType","prelude","formatTypeAnnotation","className","methodName","buildArgs","statusCode","accessor","JSON","stringify","service","cls","split","baseName","deriveBaseName","inferMethodName","hasParam","nodes","p","has","schema","renderType","source","ctxExpr","varName","suffix","isQuery","typeName","lhs","modeToWrapper","param","isValidIdentifier","renderQueryType","node","opFile","modelOutPaths","byFile","Map","unresolved","typeOutPath","get","group","set","fromDir","names","rel","startsWith","sort","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","resp","collectOutputTypeNodeRefs","out","add","forEach","paramSourceNeedsDateTime","some","typeNeedsDateTime","paramSourceNeedsScalar","typeNeedsScalar","inferredService","hasParamSource","base","pop","s","charAt","toUpperCase","slice","serviceName","template","kebab","toLowerCase","module","runIncrementalCodegen","parseIncrementalManifest","emptyIncrementalManifest","serializeIncrementalManifest","hashFingerprint","collectTransitiveModelRefs","resolveModifiers","isJsonMime","classifyContentType","basename","dirname","relative","jsonOrFormSerialize","varName","contentType","renderSerializeExpr","bodies","ctVar","arms","slice","last","length","expr","i","arm","classifyBodyStrategy","op","request","kind","body","every","b","bodyTypesStructurallyEqual","bodyType","some","hasPublicOperations","root","includeInternal","route","routes","operations","resolveModifiers","includes","generateSdk","options","lines","types","collectTypes","modelsWithInput","modelsWithOutput","clientClassName","deriveClientClassName","file","push","generateTypeImports","sdkOptionsPath","outPath","rel","relative","dirname","replace","startsWith","jsonImport","sdkNeedsJson","valueImports","sdkNeedsBigIntReplacer","sdkNeedsBigIntReviver","sdkNeedsQueryString","join","JSON_VALUE_TYPE_DECL","relFile","basename","mods","generateMethod","generateClientMethods","methodNames","deriveMethodName","methodName","httpMethod","method","toUpperCase","params","buildMethodParams","paramStr","map","p","name","optional","type","primaryResponse","responses","find","r","isVoid","respCategory","classifyContentType","dataType","renderOutputTsType","respHeaders","headers","hasRespHeaders","headersShape","h","quoteKey","headerNameToProperty","returnType","desc","description","tags","tag","urlExpr","buildUrlExpression","path","hasQuery","query","fetchUrl","strategy","hasBody","hasOpHeaders","defaultCt","nonMultipart","fetchArgs","cat","lastHeaderIdx","findIndex","a","existing","inner","resultPrefix","split","readBodyExpr","headerEntries","_","_match","nodes","renderInputTsType","typeName","has","node","ctUnion","fields","sdk","nameToMethodName","inferMethodName","parts","filter","Boolean","charAt","toLowerCase","segments","s","seg","paramName","segParts","sp","deriveBaseName","base","pop","deriveClientPropertyName","getAreaSubarea","area","meta","subarea","pascal","value","camel","deriveAreaClientClassName","deriveAreaPropertyName","deriveSubareaClientClassName","deriveSubareaPropertyName","Set","publicOps","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","resp","collectOutputTypeNodeRefs","sort","out","add","item","members","forEach","m","f","source","param","test","isJsonMime","check","src","typeNeedsScalar","items","t","key","opFile","modelOutPaths","byFile","Map","unresolved","typeOutPath","get","group","set","fromDir","names","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","template","module","generateSdkOptions","generateAreaClient","input","inlineFiles","subareaClients","className","collectedMethodLines","seenMethods","typesByImportPath","unresolvedTypes","needsJson","needsBigIntReplacer","needsBigIntReviver","needsQueryString","inline","codegenOptions","methodLines","Error","typesForFile","sdkOptionsRel","keys","importedClients","sc","client","importPath","propertyName","fetchModifier","ln","generateSdkAggregator","sdkOptionsImportPath","sdkClassName","pushClientImport","c","areas","topLevelClients","relative","dirname","computeModelsWithOutput","collectExternalOutputRefs","generatePlainTypes","root","context","externalRefs","collectExternalRefs","lines","externalModelsWithInput","modelsWithInput","Set","localModelsWithInput","computeModelsWithInput","models","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","computeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","collectExternalOutputRefs","allExternalRefs","sort","ref","importPath","resolveImportPath","push","length","rootNeedsScalar","jsonValueImportPath","JSON_VALUE_TYPE_DECL","modelMap","Map","map","m","name","model","topoSortModels","generateModel","currentOutPath","join","outPath","type","generateTypeAlias","needsInputSplit","fields","some","f","visibility","has","generateVisibilityModel","generateSimpleModel","generateOutputModel","collectInheritedFieldNames","bases","result","visit","get","add","b","computeOverrideNames","inherited","filter","override","generateComments","deprecated","description","relPath","relative","dirname","loc","file","line","renderTsType","renderInputTsType","renderOutputTsType","buildExtendsClause","overrideNames","baseNameResolver","omitKeys","n","wrapped","field","renderField","readFields","writeFields","inputResolver","renderInputField","opt","optional","default","undefined","typeStr","nullable","quoteKey","jsdocParts","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","slice","applyOutputCase","outputCase","baseExt","renderOutputField","key","resolve","join","relative","dirname","collectTypeRefs","collectPublicTypeNames","TEMPLATE_VAR_RE","resolveTemplate","template","vars","replace","_","key","includesFilename","p","last","split","pop","includes","commonDir","files","rootDir","length","resolve","parts","map","f","dirname","first","depth","i","slice","join","computeOpOutPath","filePath","baseDir","output","defaultSuffix","commonRoot","meta","baseName","relDir","relative","filename","defaultName","baseOutDir","test","resolved","dir","ext","computeContractOutPath","computeSdkOutPath","clientOutput","endsWith","defaultOutName","computeSdkAreaClientOutPath","area","fixHiddenSegment","path","segments","startsWith","subarea","cleaned","computeSdkTypeOutPath","typeOutput","generateBarrelFiles","contractPaths","byDir","Map","outPath","group","get","push","set","results","exports","sort","content","computePubliclyReachableTypes","opAsts","contractAsts","modelsWithInput","modelsWithOutput","Set","reachable","opAst","name","collectPublicTypeNames","add","modelDeps","contractAst","model","models","deps","bases","b","type","collectTypeRefs","field","fields","frontier","dep","has","inputDep","outputDep","TYPESCRIPT_CODEGEN_VERSION","CACHE_MANIFEST_FILENAME","plugin","name","generateTargets","inputs","ctx","config","options","runTypescriptCodegen","rootDir","createTypescriptPlugin","manifestPath","resolve","cacheDir","prevManifest","cacheEnabled","readManifest","emptyIncrementalManifest","units","globalFiles","server","collectServerOutput","sdk","collectSdkOutput","zod","collectZodOutput","types","collectTypesOutput","result","runIncrementalCodegen","codegenVersion","fileExists","existsSync","deleteStalePaths","deletedPaths","relativePath","content","filesToWrite","emitFile","writeManifest","manifest","buildModelMap","contractRoots","map","Map","root","model","models","set","collectContractRootRefs","modelMap","seeds","m","type","push","f","fields","bases","b","kind","collectTransitiveModelRefs","collectOpRootRefs","route","routes","params","paramSourceTypes","op","operations","query","headers","request","body","bodies","bodyType","resp","responses","h","src","out","n","nodes","node","sliceOutPathMap","refs","modelOutPaths","modelsWithInput","modelsWithOutput","slice","ref","sort","p","get","has","ip","sliceModelSet","ownNames","serverBase","baseDir","allFiles","r","file","opRoots","commonRoot","commonDir","subConfigKey","stableSubConfig","serverModelOutPaths","typeEntries","output","ast","typeOutPath","computeContractOutPath","meta","Set","fingerprint","hashFingerprint","v","outPath","outPathSlice","sub","key","render","renderCtx","currentOutPath","generateContract","generatePlainTypes","computeOpOutPath","servicePathTemplate","includeInternal","generateOp","sdkBase","sdkName","sdkOutput","sdkEntryPath","join","TEMPLATE_VAR_RE","test","resolveTemplate","sdkOptionsPath","dirname","ckCommonRoot","sdkModelOutPaths","sdkTypePaths","sdkClientInfos","sdkContractEntries","publicTypes","computePubliclyReachableTypes","computeSdkTypeOutPath","some","rel","relative","replace","startsWith","jsonValueImportPath","areaBuckets","topLevelEntries","clients","sdkOutPath","computeSdkOutPath","hasPublicOperations","area","subarea","getAreaSubarea","bucket","leaves","inlineRoots","entries","leaf","className","deriveSubareaClientClassName","propertyName","deriveSubareaPropertyName","generateSdk","typeImportPathTemplate","undefined","clientClassName","deriveClientClassName","deriveClientPropertyName","generateSdkOptions","hasAnything","length","size","areaClientOutPaths","sdkEntryDir","sdkOptionsRel","sdkOptionsImportPath","sdkClassName","split","s","charAt","toUpperCase","toClientImport","sourceDir","info","importPath","topLevelClients","e","areaInfos","sortedAreas","a","localeCompare","areaClientOutPath","computeSdkAreaClientOutPath","areaClassName","deriveAreaClientClassName","areaPropertyName","deriveAreaPropertyName","subareaClients","l","client","allInlineRefs","add","inlineFilesForGen","codegenOptions","generateAreaClient","inlineFiles","generateSdkAggregator","areas","sdkSrcDir","sdkTypeBarrels","generateBarrelFiles","barrel","rootExports","basename","c","zodBase","typesBase","parseIncrementalManifest","readFileSync","mkdirSync","recursive","writeFileSync","serializeIncrementalManifest","absPaths","removedDirs","abs","rmSync","force","dir","current","readdirSync","rmdirSync","JSON","stringify"]}