Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | 14x 14x 14x 14x 14x 14x 14x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 14x 13x 13x 13x 4x 4x 4x 4x 4x 4x 4x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 2x 2x 2x 3x 2x 2x 2x 1x 4x 2x 2x 2x 4x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 4x 1x 1x 4x 3x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 4x 4x 1x 1x 1x 1x 1x 1x 1x 17x 17x 13x 17x 4x 17x 17x | import { resolve, join, relative, dirname, basename } from 'node:path';
import { generateContract } from './codegen-contract.js';
import { generateOp } from './codegen-operation.js';
import type { ContractKitPlugin } from '@contractkit/core';
import {
generateSdk,
generateSdkOptions,
generateSdkAggregator,
deriveClientClassName,
deriveClientPropertyName,
deriveSubareaClientClassName,
deriveSubareaPropertyName,
getAreaSubarea,
hasPublicOperations,
type SdkClientInfo,
type SdkAreaInfo,
} from './codegen-sdk.js';
import { generatePlainTypes } from './codegen-plain-types.js';
import {
TEMPLATE_VAR_RE,
resolveTemplate,
commonDir,
computeOpOutPath,
computeContractOutPath,
computeSdkOutPath,
computeSdkTypeOutPath,
generateBarrelFiles,
computePubliclyReachableTypes,
} from './path-utils.js';
// ─── Sub-config interfaces ─────────────────────────────────────────────────
export interface ServerConfig {
/** Directory (relative to rootDir) where server files are written. Default: rootDir. */
baseDir?: string;
/**
* When true, `output.types` emits Zod schema files (via `generateContract`).
* When false/omitted, `output.types` emits plain TypeScript interfaces.
*/
zod?: boolean;
output?: {
/** Path template for Koa router files. Supports {filename}, {dir}, {area}. Default: `{filename}.router.ts`. */
routes?: string;
/**
* Path template for type/schema files. Supports {filename}, {dir}, {area}.
* Generates Zod schemas when `zod: true`, otherwise plain TypeScript interfaces.
*/
types?: string;
};
/** Import path template for service implementations. Supports {module}. */
servicePathTemplate?: string;
/**
* Whether to emit handlers for operations marked `internal`. Defaults to `true` —
* the server still needs routes for internal endpoints. Set to `false` to omit them.
*/
includeInternal?: boolean;
}
export interface SdkConfig {
/** Directory (relative to rootDir) where SDK files are written. Default: rootDir. */
baseDir?: string;
/** Name used for the aggregator SDK class (e.g. "homegrown" → `HomegrownSdk`). */
name?: string;
/**
* When true, `output.types` emits Zod schema files (via `generateContract`).
* When false/omitted, `output.types` emits plain TypeScript interfaces.
*/
zod?: boolean;
output?: {
/** Path template for the SDK aggregator file. Supports {name}. Default: `sdk.ts`. */
sdk?: string;
/** Path template for SDK type files. Supports {filename}, {dir}, {area}, {subarea}. */
types?: string;
/** Path template for client class files. Supports {filename}, {dir}, {area}, {subarea}. */
clients?: string;
};
/**
* Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —
* internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`
* for an internal-use SDK that should expose them.
*/
includeInternal?: boolean;
}
export interface ZodConfig {
/** Directory (relative to rootDir) where Zod schema files are written. Default: rootDir. */
baseDir?: string;
/** Output path template. Supports {filename}, {dir}. Default: `{filename}.schema.ts` alongside source. */
output?: string;
}
export interface TypesConfig {
/** Directory (relative to rootDir) where plain TypeScript type files are written. Default: rootDir. */
baseDir?: string;
/** Output path template. Supports {filename}, {dir}. Default: `{filename}.types.ts` alongside source. */
output?: string;
}
export interface TypescriptPluginConfig {
/** Generate Koa router files from `operation` declarations. */
server?: ServerConfig;
/** Generate TypeScript SDK client files from `operation` declarations. */
sdk?: SdkConfig;
/** Generate Zod schema files from `contract` declarations. */
zod?: ZodConfig;
/** Generate plain TypeScript interface/type files from `contract` declarations (no Zod runtime). */
types?: TypesConfig;
}
// ─── Server generation ─────────────────────────────────────────────────────
function runServerGeneration(
config: ServerConfig,
rootDir: string,
inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
emitFile: (outPath: string, content: string) => void,
): void {
const serverBase = resolve(rootDir, config.baseDir ?? '.');
const modelsWithInput = inputs.modelsWithInput as Set<string>;
const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
const commonRoot = commonDir(allFiles, rootDir);
// ── Types / Zod output ──
// When output.types is configured we generate type files ourselves and build a
// local modelOutPaths map so the router generator can resolve import paths.
let serverModelOutPaths = new Map<string, string>();
if (config.output?.types) {
serverModelOutPaths = new Map();
// Pass 1: register all model → outPath entries before generating content,
// so cross-file type refs resolve correctly.
const typeEntries: { ast: (typeof inputs.contractRoots)[number]; typeOutPath: string }[] = [];
for (const ast of inputs.contractRoots) {
const typeOutPath = computeContractOutPath(ast.file, serverBase, config.output.types, '.ts', commonRoot, ast.meta);
typeEntries.push({ ast, typeOutPath });
for (const model of ast.models) {
serverModelOutPaths.set(model.name, typeOutPath);
Iif (modelsWithInput.has(model.name)) {
serverModelOutPaths.set(`${model.name}Input`, typeOutPath);
}
Iif (modelsWithOutput.has(model.name)) {
serverModelOutPaths.set(`${model.name}Output`, typeOutPath);
}
}
}
// Pass 2: emit type files.
for (const { ast, typeOutPath } of typeEntries) {
const ctx = { modelOutPaths: serverModelOutPaths, currentOutPath: typeOutPath, modelsWithInput, modelsWithOutput };
const content = config.zod ? generateContract(ast, ctx) : generatePlainTypes(ast, ctx);
emitFile(typeOutPath, content);
}
}
// ── Routes output ──
for (const ast of inputs.opRoots) {
const outPath = computeOpOutPath(ast.file, serverBase, config.output?.routes, '.router.ts', commonRoot, ast.meta);
const content = generateOp(ast, {
servicePathTemplate: config.servicePathTemplate,
outPath,
modelOutPaths: serverModelOutPaths,
modelsWithInput,
modelsWithOutput,
includeInternal: config.includeInternal,
});
emitFile(outPath, content);
}
}
// ─── SDK generation ────────────────────────────────────────────────────────
function runSdkGeneration(
config: SdkConfig,
rootDir: string,
inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
emitFile: (outPath: string, content: string) => void,
): void {
const sdkBase = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;
const sdkName = config.name;
const sdkOutput = config.output?.sdk;
const sdkEntryPath = sdkOutput
? join(sdkBase, TEMPLATE_VAR_RE.test(sdkOutput) ? resolveTemplate(sdkOutput, { name: sdkName ?? 'sdk' }) : sdkOutput)
: join(sdkBase, 'sdk.ts');
const sdkOptionsPath = join(dirname(sdkEntryPath), 'sdk-options.ts');
const modelsWithInput = inputs.modelsWithInput as Set<string>;
const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
const ckCommonRoot = commonDir(allFiles, rootDir);
let sdkModelOutPaths = new Map<string, string>();
const sdkTypePaths: string[] = [];
const sdkClientInfos: { outPath: string; className: string; propertyName: string }[] = [];
// ── SDK types ──
Iif (config.output?.types) {
sdkModelOutPaths = new Map<string, string>();
const publicTypes = computePubliclyReachableTypes(inputs.opRoots, inputs.contractRoots, modelsWithInput, modelsWithOutput);
const sdkContractEntries: { ast: (typeof inputs.contractRoots)[number]; typeOutPath: string }[] = [];
for (const ast of inputs.contractRoots) {
const typeOutPath = computeSdkTypeOutPath(ast.file, sdkBase, config.output.types, ckCommonRoot, ast.meta);
if (!typeOutPath) continue;
if (publicTypes !== null && !ast.models.some(m => publicTypes.has(m.name))) continue;
sdkTypePaths.push(typeOutPath);
sdkContractEntries.push({ ast, typeOutPath });
for (const model of ast.models) {
sdkModelOutPaths.set(model.name, typeOutPath);
if (modelsWithInput.has(model.name)) sdkModelOutPaths.set(`${model.name}Input`, typeOutPath);
if (modelsWithOutput.has(model.name)) sdkModelOutPaths.set(`${model.name}Output`, typeOutPath);
}
}
for (const { ast, typeOutPath } of sdkContractEntries) {
let content: string;
if (config.zod) {
content = generateContract(ast, {
modelOutPaths: sdkModelOutPaths,
currentOutPath: typeOutPath,
modelsWithInput,
modelsWithOutput,
});
} else {
let rel = relative(dirname(typeOutPath), sdkOptionsPath).replace(/\.ts$/, '.js');
if (!rel.startsWith('.')) rel = './' + rel;
content = generatePlainTypes(ast, {
modelOutPaths: sdkModelOutPaths,
currentOutPath: typeOutPath,
modelsWithInput,
modelsWithOutput,
jsonValueImportPath: rel,
});
}
emitFile(typeOutPath, content);
}
}
// ── SDK clients ──
// Group opRoots by (area, subarea):
// - area + subarea → leaf client emitted as <Area><Subarea>Client in its own file
// - area only → no standalone file; methods inlined into <Area>Client in sdk.ts
// - neither → flat top-level client (legacy behavior)
interface AreaBucket {
leaves: { ast: typeof inputs.opRoots[number]; outPath: string; subarea: string }[];
inlineRoots: typeof inputs.opRoots[number][];
}
const areaBuckets = new Map<string, AreaBucket>();
const topLevelEntries: { ast: typeof inputs.opRoots[number]; outPath: string }[] = [];
Eif (config.output?.clients) {
for (const ast of inputs.opRoots) {
const sdkOutPath = computeSdkOutPath(ast.file, sdkBase, config.output.clients, ckCommonRoot, ast.meta);
Iif (!sdkOutPath || !hasPublicOperations(ast, config.includeInternal)) continue;
const { area, subarea } = getAreaSubarea(ast);
if (area && subarea) {
const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };
bucket.leaves.push({ ast, outPath: sdkOutPath, subarea });
areaBuckets.set(area, bucket);
} else if (area) {
const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };
bucket.inlineRoots.push(ast);
areaBuckets.set(area, bucket);
} else {
topLevelEntries.push({ ast, outPath: sdkOutPath });
}
}
// Emit per-file clients for leaves (subarea) and top-level (no area). Area-only files are inlined later.
for (const { ast, outPath, subarea } of [...areaBuckets.entries()].flatMap(([area, b]) => b.leaves.map(l => ({ ...l, area })))) {
const className = deriveSubareaClientClassName((ast.meta?.area as string) ?? '', subarea);
sdkClientInfos.push({ outPath, className, propertyName: deriveSubareaPropertyName(subarea) });
emitFile(
outPath,
generateSdk(ast, {
typeImportPathTemplate: undefined,
outPath,
modelOutPaths: sdkModelOutPaths,
sdkOptionsPath,
modelsWithInput,
modelsWithOutput,
includeInternal: config.includeInternal,
clientClassName: className,
}),
);
}
for (const { ast, outPath } of topLevelEntries) {
const className = deriveClientClassName(ast.file);
sdkClientInfos.push({ outPath, className, propertyName: deriveClientPropertyName(ast.file) });
emitFile(
outPath,
generateSdk(ast, {
typeImportPathTemplate: undefined,
outPath,
modelOutPaths: sdkModelOutPaths,
sdkOptionsPath,
modelsWithInput,
modelsWithOutput,
includeInternal: config.includeInternal,
}),
);
}
}
// ── sdk-options.ts ──
emitFile(sdkOptionsPath, generateSdkOptions());
// ── sdk.ts aggregator ──
const hasAnything = sdkClientInfos.length > 0 || areaBuckets.size > 0;
Eif (hasAnything) {
const sdkEntryDir = dirname(sdkEntryPath);
const sdkOptionsRel = relative(sdkEntryDir, sdkOptionsPath).replace(/\.ts$/, '.js');
const sdkOptionsImportPath = sdkOptionsRel.startsWith('.') ? sdkOptionsRel : './' + sdkOptionsRel;
const sdkClassName = sdkName
? sdkName
.split(/[-._\s]+/)
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join('') + 'Sdk'
: 'Sdk';
const toClientImport = (info: { outPath: string; className: string; propertyName: string }): SdkClientInfo => {
let rel = relative(sdkEntryDir, info.outPath).replace(/\.ts$/, '.js');
Eif (!rel.startsWith('.')) rel = './' + rel;
return { className: info.className, propertyName: info.propertyName, importPath: rel };
};
const topLevelClients: SdkClientInfo[] = topLevelEntries.map(e => ({
className: deriveClientClassName(e.ast.file),
propertyName: deriveClientPropertyName(e.ast.file),
importPath: (() => {
const rel = relative(sdkEntryDir, e.outPath).replace(/\.ts$/, '.js');
return rel.startsWith('.') ? rel : './' + rel;
})(),
}));
const areas: SdkAreaInfo[] = [...areaBuckets.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([area, bucket]) => ({
area,
inlineFiles: bucket.inlineRoots.map(root => ({
root,
codegenOptions: {
typeImportPathTemplate: undefined,
outPath: sdkEntryPath,
modelOutPaths: sdkModelOutPaths,
sdkOptionsPath,
modelsWithInput,
modelsWithOutput,
includeInternal: config.includeInternal,
},
})),
subareaClients: bucket.leaves
.sort((a, b) => a.subarea.localeCompare(b.subarea))
.map(l => ({
propertyName: deriveSubareaPropertyName(l.subarea),
client: toClientImport({
outPath: l.outPath,
className: deriveSubareaClientClassName(area, l.subarea),
propertyName: deriveSubareaPropertyName(l.subarea),
}),
})),
}));
emitFile(
sdkEntryPath,
generateSdkAggregator({
topLevelClients,
areas,
sdkOptionsImportPath,
sdkClassName,
}),
);
}
// ── Barrel files ──
const sdkSrcDir = dirname(sdkEntryPath);
const sdkTypeBarrels = generateBarrelFiles(sdkTypePaths);
for (const barrel of sdkTypeBarrels) emitFile(barrel.outPath, barrel.content);
const rootExports: string[] = [`export * from './${basename(sdkOptionsPath).replace(/\.ts$/, '.js')}';`];
Eif (hasAnything) {
rootExports.push(`export * from './${basename(sdkEntryPath).replace(/\.ts$/, '.js')}';`);
}
for (const c of sdkClientInfos) {
let rel = relative(sdkSrcDir, c.outPath).replace(/\.ts$/, '.js');
Eif (!rel.startsWith('.')) rel = './' + rel;
rootExports.push(`export * from '${rel}';`);
}
for (const barrel of sdkTypeBarrels) {
let rel = relative(sdkSrcDir, barrel.outPath).replace(/\.ts$/, '.js');
if (!rel.startsWith('.')) rel = './' + rel;
rootExports.push(`export * from '${rel}';`);
}
emitFile(join(sdkSrcDir, 'index.ts'), `// Auto-generated barrel file\n${rootExports.sort().join('\n')}\n`);
}
// ─── Zod generation ────────────────────────────────────────────────────────
function runZodGeneration(
config: ZodConfig,
rootDir: string,
inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
emitFile: (outPath: string, content: string) => void,
): void {
const zodBase = resolve(rootDir, config.baseDir ?? '.');
const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
const commonRoot = commonDir(allFiles, rootDir);
const modelsWithInput = inputs.modelsWithInput as Set<string>;
const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
// Pre-pass: register all model → outPath before generating, so cross-file imports resolve.
const modelOutPaths = new Map<string, string>();
const entries: { ast: (typeof inputs.contractRoots)[number]; outPath: string }[] = [];
for (const ast of inputs.contractRoots) {
const outPath = computeContractOutPath(ast.file, zodBase, config.output, '.schema.ts', commonRoot, ast.meta);
entries.push({ ast, outPath });
for (const model of ast.models) {
modelOutPaths.set(model.name, outPath);
if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);
if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);
}
}
for (const { ast, outPath } of entries) {
const content = generateContract(ast, {
modelOutPaths,
currentOutPath: outPath,
modelsWithInput,
modelsWithOutput,
});
emitFile(outPath, content);
}
}
// ─── Types generation ──────────────────────────────────────────────────────
function runTypesGeneration(
config: TypesConfig,
rootDir: string,
inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
emitFile: (outPath: string, content: string) => void,
): void {
const typesBase = resolve(rootDir, config.baseDir ?? '.');
const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
const commonRoot = commonDir(allFiles, rootDir);
const modelsWithInput = inputs.modelsWithInput as Set<string>;
const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
// Pre-pass: register all model → outPath before generating.
const modelOutPaths = new Map<string, string>();
const entries: { ast: (typeof inputs.contractRoots)[number]; outPath: string }[] = [];
for (const ast of inputs.contractRoots) {
const outPath = computeContractOutPath(ast.file, typesBase, config.output, '.types.ts', commonRoot, ast.meta);
entries.push({ ast, outPath });
for (const model of ast.models) {
modelOutPaths.set(model.name, outPath);
if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);
if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);
}
}
for (const { ast, outPath } of entries) {
const content = generatePlainTypes(ast, {
modelOutPaths,
currentOutPath: outPath,
modelsWithInput,
modelsWithOutput,
});
emitFile(outPath, content);
}
}
// ─── Combined plugin ────────────────────────────────────────────────────────
const plugin: ContractKitPlugin = {
name: 'typescript',
cacheKey: 'typescript',
async generateTargets(inputs, ctx) {
const config = ctx.options as TypescriptPluginConfig;
Eif (config.server) {
runServerGeneration(config.server, ctx.rootDir, inputs, ctx.emitFile.bind(ctx));
}
Iif (config.sdk) {
runSdkGeneration(config.sdk, ctx.rootDir, inputs, ctx.emitFile.bind(ctx));
}
Iif (config.zod) {
runZodGeneration(config.zod, ctx.rootDir, inputs, ctx.emitFile.bind(ctx));
}
Iif (config.types) {
runTypesGeneration(config.types, ctx.rootDir, inputs, ctx.emitFile.bind(ctx));
}
},
};
export default plugin;
// ─── Factory: for programmatic use with explicit config ────────────────────
/**
* Build a `@contractkit/plugin-typescript` instance with explicit configuration, for
* programmatic use (tests, custom build scripts). Prefer the default export when loading
* via `contractkit.config.json`.
*/
export function createTypescriptPlugin(config: TypescriptPluginConfig, rootDir: string): ContractKitPlugin {
return {
name: 'typescript',
cacheKey: `typescript:${JSON.stringify(config)}`,
async generateTargets(inputs, ctx) {
if (config.server) {
runServerGeneration(config.server, rootDir, inputs, ctx.emitFile.bind(ctx));
}
if (config.sdk) {
runSdkGeneration(config.sdk, rootDir, inputs, ctx.emitFile.bind(ctx));
}
Iif (config.zod) {
runZodGeneration(config.zod, rootDir, inputs, ctx.emitFile.bind(ctx));
}
Iif (config.types) {
runTypesGeneration(config.types, rootDir, inputs, ctx.emitFile.bind(ctx));
}
},
};
}
|