All files / src codegen-client.ts

82.6% Statements 266/322
77.92% Branches 180/231
86.48% Functions 32/37
83.33% Lines 235/282

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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663                                                      2x 2x 2x     1x             25x 25x 25x     25x   25x 25x 25x 25x     25x 25x 25x 25x 25x   25x             25x     25x 25x 30x 30x 28x     25x 28x 28x     25x 2x 2x 2x 2x   25x     25x 25x 35x 26x 35x 2x 2x 1x 1x   2x     25x 1x 1x       25x 2x 2x 2x 2x 2x 2x 3x 3x 3x       25x 25x 25x   25x 25x 30x 30x 30x 28x 28x 28x 28x       25x       25x   25x                         28x 28x 28x 28x   28x 28x 28x 17x 16x   28x     28x 28x 28x 28x             28x 28x 28x 28x 28x 28x     28x 28x 2x 2x 2x 2x 2x   26x       28x     28x 28x 28x 28x 28x     28x 28x   28x 28x 7x 7x   7x   1x 6x 6x             7x 2x   7x 1x     28x 2x     28x 1x     28x       28x   28x 2x 2x   26x     28x 3x 1x   2x       25x 3x 3x 22x 20x   2x   25x 1x   24x       28x         2x 2x 2x 3x 3x 3x   2x         4x     8x               28x 28x 9x 9x           28x     28x 9x 9x 9x                                 28x 28x 7x 7x   7x 1x   6x 6x 6x         28x 1x 1x       28x         28x       1x       1x         1x           6x           32x 3x 3x       23x 20x 20x       3x                     25x   25x 30x 30x   28x 28x 7x   28x 28x   28x 28x       25x       10x   10x 11x             31x 31x 31x         46x   11x                     9x 9x             11x   32x 1x   31x   32x   3x 3x                                                           28x       28x   29x         28x         2x       2x 2x                 30x 16x 15x       35x 15x   15x 20x 5x 5x   15x       15x       35x                   1x                                                                                                                                                                            
import type { OpRootNode, OpRouteNode, OpOperationNode, OpResponseHeaderNode, ContractTypeNode, ParamSource } from '@contractkit/core';
import { resolveModifiers, classifyContentType } from '@contractkit/core';
import { renderPyType, toPythonFieldName } from './codegen-models.js';
 
// ─── Public entry point ────────────────────────────────────────────────────
 
export interface ClientCodegenOptions {
    /** Map from model name → Python module path (e.g. "._models_payments") */
    modelModulePaths?: Map<string, string>;
    /** Current client's module name (e.g. "_client_payments") — used to avoid self-imports */
    currentModule?: string;
    /** Set of model names that have Input variants */
    modelsWithInput?: Set<string>;
    /**
     * Whether to emit client methods for operations marked `internal`. Defaults to `false` —
     * internal ops are omitted so consumers don't pick them up. Set to `true` for an
     * internal-use SDK that should expose them.
     */
    includeInternal?: boolean;
}
 
/**
 * Returns true if the root contains at least one operation eligible for client emission.
 * With `includeInternal: false` (default) that means at least one non-internal op; with
 * `includeInternal: true` any op qualifies.
 */
export function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {
    for (const route of root.routes) {
        for (const op of route.operations) {
            if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;
        }
    }
    return false;
}
 
/**
 * Generate a Pydantic/httpx async Python client class from an OpRootNode.
 */
export function generatePythonClient(root: OpRootNode, opts: ClientCodegenOptions = {}): string {
    const clientClassName = deriveClientClassName(root.file);
    const { modelsWithInput } = opts;
    const includeInternal = opts.includeInternal ?? false;
 
    // Collect all model types referenced in public ops
    const referencedModels = collectReferencedModels(root, modelsWithInput, includeInternal);
 
    const lines: string[] = [];
    lines.push('# Auto-generated by contractkit-plugin-python-sdk. Do not edit manually.');
    lines.push('from __future__ import annotations');
    lines.push('');
 
    // stdlib imports
    const needsDatetime = referencedModels.has('__datetime__');
    const needsDate = referencedModels.has('__date__');
    const needsTime = referencedModels.has('__time__');
    const needsUUID = referencedModels.has('__uuid__');
    const needsAny = referencedModels.has('__any__');
 
    Iif (needsDatetime || needsDate || needsTime) {
        const dtParts: string[] = [];
        if (needsDate) dtParts.push('date');
        if (needsDatetime) dtParts.push('datetime');
        if (needsTime) dtParts.push('time');
        lines.push(`from datetime import ${dtParts.join(', ')}`);
    }
    if (needsUUID) lines.push('from uuid import UUID');
 
    // Collect public ops once — used both for TypedDict emission and method generation.
    const publicOps: Array<{ route: OpRouteNode; op: OpOperationNode }> = [];
    for (const route of root.routes) {
        for (const op of route.operations) {
            if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
            publicOps.push({ route, op });
        }
    }
    const opsWithRespHeaders = publicOps.filter(({ op }) => {
        const primary = op.responses.find(r => r.bodyType) ?? op.responses[0];
        return (primary?.headers?.length ?? 0) > 0;
    });
 
    if (needsAny || opsWithRespHeaders.length > 0) {
        const typingImports: string[] = [];
        Iif (needsAny) typingImports.push('Any');
        Eif (opsWithRespHeaders.length > 0) typingImports.push('TypedDict');
        lines.push(`from typing import ${typingImports.join(', ')}`);
    }
    lines.push('from ._base_client import BaseClient, SdkError  # noqa: F401');
 
    // Model imports grouped by module
    const modelImportsByModule = new Map<string, Set<string>>();
    for (const name of referencedModels) {
        if (name.startsWith('__')) continue; // sentinel keys
        const modulePath = opts.modelModulePaths?.get(name);
        if (modulePath) {
            let s = modelImportsByModule.get(modulePath);
            if (!s) {
                s = new Set();
                modelImportsByModule.set(modulePath, s);
            }
            s.add(name);
        }
    }
    for (const [mod, names] of [...modelImportsByModule].sort((a, b) => a[0].localeCompare(b[0]))) {
        const sorted = [...names].sort().join(', ');
        lines.push(`from ${mod} import ${sorted}`);
    }
 
    // Per-method response-header TypedDicts.
    for (const { route, op } of opsWithRespHeaders) {
        const primary = op.responses.find(r => r.bodyType) ?? op.responses[0]!;
        const className = `${snakeToPascal(deriveMethodName(op, route))}Headers`;
        lines.push('');
        lines.push('');
        lines.push(`class ${className}(TypedDict, total=False):`);
        for (const h of primary.headers!) {
            const pyName = toPythonFieldName(h.name);
            const tag = h.optional ? 'optional' : 'required';
            lines.push(`    ${pyName}: str  # ${h.name} (${tag})`);
        }
    }
 
    lines.push('');
    lines.push('');
    lines.push(`class ${clientClassName}(BaseClient):`);
 
    let hasAnyMethod = false;
    for (const route of root.routes) {
        for (const op of route.operations) {
            const mods = resolveModifiers(route, op);
            if (!includeInternal && mods.includes('internal')) continue;
            hasAnyMethod = true;
            lines.push('');
            if (mods.includes('deprecated')) lines.push('    # @deprecated');
            lines.push(...generateMethod(route, op, opts));
        }
    }
 
    Iif (!hasAnyMethod) {
        lines.push('    pass');
    }
 
    lines.push('');
 
    return lines.join('\n');
}
 
// ─── Method generation ────────────────────────────────────────────────────
 
interface MethodParam {
    name: string;
    type: string;
    optional: boolean;
    isModel: boolean; // Pydantic BaseModel → use .model_dump(mode="json")
}
 
function generateMethod(route: OpRouteNode, op: OpOperationNode, opts: ClientCodegenOptions): string[] {
    const lines: string[] = [];
    const { modelsWithInput } = opts;
    const methodName = deriveMethodName(op, route);
    const httpMethod = op.method.toUpperCase();
 
    const params = buildMethodParams(route, op, modelsWithInput);
    const selfParam = 'self';
    const allParams = params.map(p => {
        if (p.optional) return `${p.name}: ${p.type} | None = None`;
        return `${p.name}: ${p.type}`;
    });
    const paramStr = allParams.length > 0 ? `, ${allParams.join(', ')}` : '';
 
    // Return type — non-JSON responses ignore the schema and return raw bytes/str.
    const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];
    const isVoid = !primaryResponse?.bodyType;
    const respCategory = primaryResponse?.contentType ? classifyContentType(primaryResponse.contentType) : 'json';
    const dataType = isVoid
        ? 'None'
        : respCategory === 'text'
          ? 'str'
          : respCategory === 'binary'
            ? 'bytes'
            : renderPyType(primaryResponse!.bodyType!, modelsWithInput);
    const isModelReturn = !isVoid && respCategory === 'json' && isModelRef(primaryResponse!.bodyType!, modelsWithInput);
    const isListModelReturn = !isVoid && respCategory === 'json' && isListModelRef(primaryResponse!.bodyType!, modelsWithInput);
    const respHeaders = primaryResponse?.headers ?? [];
    const hasRespHeaders = respHeaders.length > 0;
    const headersTypeName = hasRespHeaders ? `${snakeToPascal(methodName)}Headers` : '';
    const returnType = hasRespHeaders ? (isVoid ? headersTypeName : `tuple[${dataType}, ${headersTypeName}]`) : dataType;
 
    // Description
    const desc = op.description ?? route.description;
    if (op.name || desc) {
        lines.push(`    async def ${methodName}(${selfParam}${paramStr}) -> ${returnType}:`);
        lines.push(`        """`);
        Eif (op.name) lines.push(`        ${op.name}`);
        Iif (desc) lines.push(`        ${desc}`);
        lines.push(`        """`);
    } else {
        lines.push(`    async def ${methodName}(${selfParam}${paramStr}) -> ${returnType}:`);
    }
 
    // Build URL
    const urlExpr = buildUrlExpression(route.path);
 
    // Query params
    const hasQuery = !!op.query;
    const primaryBody = op.request?.bodies[0];
    const hasBody = !!primaryBody;
    const isMultipart = primaryBody?.contentType === 'multipart/form-data';
    const hasCustomHeaders = !!op.headers;
 
    // Build kwargs for _fetch
    const fetchKwargs: string[] = [];
    fetchKwargs.push(`method="${httpMethod}"`);
 
    const reqCategory = primaryBody?.contentType ? classifyContentType(primaryBody.contentType) : 'json';
    if (hasBody) {
        const bodyParam = params.find(p => p.name === 'body');
        Iif (isMultipart) {
            fetchKwargs.push('body=body');
        } else if (reqCategory === 'text' || reqCategory === 'binary') {
            // Pass-through: caller supplies a str / bytes payload that goes on the wire as-is.
            fetchKwargs.push('body=body');
        } else if (bodyParam?.isModel) {
            fetchKwargs.push('body=body.model_dump(mode="json")');
        } else E{
            fetchKwargs.push('body=body');
        }
        // Forward the declared content-type so `_fetch` sets the correct Content-Type header
        // (vendor JSON types like `application/vnd.api+json` still serialize as JSON but need
        // their literal mime on the wire).
        if (primaryBody.contentType !== 'application/json') {
            fetchKwargs.push(`content_type=${JSON.stringify(primaryBody.contentType)}`);
        }
        if (reqCategory === 'text' || reqCategory === 'binary') {
            fetchKwargs.push(`body_kind="${reqCategory}"`);
        }
    }
    if (respCategory === 'text' || respCategory === 'binary') {
        fetchKwargs.push(`response_kind="${respCategory}"`);
    }
 
    if (hasQuery) {
        fetchKwargs.push('params=query');
    }
 
    Iif (hasCustomHeaders) {
        fetchKwargs.push('extra_headers=custom_headers');
    }
 
    const kwargsStr = fetchKwargs.length > 1 ? fetchKwargs.join(', ') : (fetchKwargs[0] ?? '');
 
    if (hasRespHeaders) {
        lines.push(`        result, _response_headers = await self._fetch_with_headers(${urlExpr}, ${kwargsStr})`);
        lines.push(...buildHeadersDictLines(respHeaders, headersTypeName));
    } else {
        lines.push(`        result = await self._fetch(${urlExpr}, ${kwargsStr})`);
    }
 
    if (isVoid) {
        if (hasRespHeaders) {
            lines.push(`        return headers`);
        } else {
            lines.push(`        return None`);
        }
    } else {
        let dataExpr: string;
        if (isListModelReturn) {
            const innerType = getListItemType(primaryResponse!.bodyType!, modelsWithInput);
            dataExpr = `[${innerType}.model_validate(item) for item in result]`;
        } else if (isModelReturn) {
            dataExpr = `${dataType}.model_validate(result)`;
        } else {
            dataExpr = 'result';
        }
        if (hasRespHeaders) {
            lines.push(`        return ${dataExpr}, headers`);
        } else {
            lines.push(`        return ${dataExpr}`);
        }
    }
 
    return lines;
}
 
/** Build the lines that construct a TypedDict literal of declared response headers. */
function buildHeadersDictLines(headers: OpResponseHeaderNode[], typeName: string): string[] {
    const lines: string[] = [];
    lines.push(`        headers: ${typeName} = {}`);
    for (const h of headers) {
        const pyName = toPythonFieldName(h.name);
        lines.push(`        if ${JSON.stringify(h.name.toLowerCase())} in _response_headers:`);
        lines.push(`            headers[${JSON.stringify(pyName)}] = _response_headers[${JSON.stringify(h.name.toLowerCase())}]`);
    }
    return lines;
}
 
/** snake_case → PascalCase. */
function snakeToPascal(s: string): string {
    return s
        .split('_')
        .filter(Boolean)
        .map(p => p.charAt(0).toUpperCase() + p.slice(1))
        .join('');
}
 
// ─── URL building ─────────────────────────────────────────────────────────
 
function buildUrlExpression(path: string): string {
    // Replace {paramName} with Python f-string interpolation
    const hasBraces = /\{[a-zA-Z_][a-zA-Z0-9_]*\}/.test(path);
    if (!hasBraces) return `"${path}"`;
    const interpolated = path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_m, name) => `{${name}}`);
    return `f"${interpolated}"`;
}
 
// ─── Parameter building ───────────────────────────────────────────────────
 
function buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {
    const params: MethodParam[] = [];
 
    // Path params
    if (route.params) {
        if (route.params.kind === 'params') {
            for (const p of route.params.nodes) {
                params.push({
                    name: toPythonFieldName(p.name),
                    type: renderPyType(p.type, modelsWithInput),
                    optional: false,
                    isModel: false,
                });
            }
        } else Eif (route.params.kind === 'ref') {
            const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;
            params.push({ name: 'params', type: typeName, optional: false, isModel: true });
        } else {
            params.push({ name: 'params', type: renderPyType(route.params.node, modelsWithInput), optional: false, isModel: false });
        }
    }
 
    // Body — use the first declared MIME's body type as the parameter type.
    // Multi-MIME support in Python collapses to a single signature using the primary body.
    const primaryBody = op.request?.bodies[0];
    if (primaryBody) {
        const cat = classifyContentType(primaryBody.contentType);
        Iif (cat === 'multipart' || cat === 'binary') {
            params.push({ name: 'body', type: 'bytes', optional: false, isModel: false });
        } else if (cat === 'text') {
            params.push({ name: 'body', type: 'str', optional: false, isModel: false });
        } else {
            const bodyType = renderInputPyType(primaryBody.bodyType, modelsWithInput);
            const isModel = isModelRef(primaryBody.bodyType, modelsWithInput);
            params.push({ name: 'body', type: bodyType, optional: false, isModel });
        }
    }
 
    // Query
    if (op.query) {
        const queryType = renderParamSourceType(op.query, modelsWithInput, true);
        params.push({ name: 'query', type: queryType, optional: true, isModel: false });
    }
 
    // Headers
    Iif (op.headers) {
        const headersType = renderParamSourceType(op.headers, modelsWithInput, true);
        params.push({ name: 'custom_headers', type: headersType, optional: true, isModel: false });
    }
 
    return params;
}
 
function renderParamSourceType(source: ParamSource, modelsWithInput?: Set<string>, forInput = false): string {
    Iif (source.kind === 'ref') {
        const typeName = forInput && modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;
        return typeName;
    }
    Eif (source.kind === 'params') {
        // const fields = source.nodes.map(p => {
        //     const pyName = toPythonFieldName(p.name);
        //     return `"${pyName}": ${renderPyType(p.type, modelsWithInput, forInput)}`;
        // });
        return `dict`; // simplified — inline dicts are hard to type concisely in Python signatures
    }
    return renderPyType(source.node, modelsWithInput, forInput);
}
 
function renderInputPyType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {
    return renderPyType(type, modelsWithInput, true);
}
 
// ─── Model reference detection ────────────────────────────────────────────
 
function isModelRef(type: ContractTypeNode, modelsWithInput?: Set<string>): boolean {
    if (type.kind === 'ref') return /^[A-Z]/.test(type.name);
    Iif (type.kind === 'lazy') return isModelRef(type.inner, modelsWithInput);
    return false;
}
 
function isListModelRef(type: ContractTypeNode, modelsWithInput?: Set<string>): boolean {
    if (type.kind === 'array') return isModelRef(type.item, modelsWithInput);
    Iif (type.kind === 'lazy') return isListModelRef(type.inner, modelsWithInput);
    return false;
}
 
function getListItemType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {
    Eif (type.kind === 'array') return renderPyType(type.item, modelsWithInput);
    return 'dict';
}
 
// ─── Referenced model collection ─────────────────────────────────────────
 
/**
 * Collect all model names and scalar sentinels referenced in public operations.
 * Sentinels: __datetime__, __date__, __time__, __uuid__, __any__
 */
function collectReferencedModels(root: OpRootNode, modelsWithInput?: Set<string>, includeInternal = false): Set<string> {
    const refs = new Set<string>();
 
    for (const route of root.routes) {
        for (const op of route.operations) {
            if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
 
            if (route.params) collectParamSourceRefs(route.params, refs, modelsWithInput);
            if (op.request) {
                for (const body of op.request.bodies) collectTypeRefs(body.bodyType, refs, modelsWithInput, true);
            }
            for (const resp of op.responses) {
                if (resp.bodyType) collectTypeRefs(resp.bodyType, refs, modelsWithInput, false);
            }
            if (op.query) collectParamSourceRefs(op.query, refs, modelsWithInput);
            Iif (op.headers) collectParamSourceRefs(op.headers, refs, modelsWithInput);
        }
    }
 
    return refs;
}
 
function collectParamSourceRefs(source: ParamSource, out: Set<string>, modelsWithInput?: Set<string>): void {
    Iif (source.kind === 'ref') {
        addModelRef(source.name, out, modelsWithInput);
    } else if (source.kind === 'params') {
        for (const p of source.nodes) collectTypeRefs(p.type, out, modelsWithInput);
    } else E{
        collectTypeRefs(source.node, out, modelsWithInput);
    }
}
 
function addModelRef(name: string, out: Set<string>, modelsWithInput?: Set<string>): void {
    Eif (/^[A-Z]/.test(name)) {
        out.add(name);
        if (modelsWithInput?.has(name)) out.add(`${name}Input`);
    }
}
 
function collectTypeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>, forInput = false): void {
    switch (type.kind) {
        case 'scalar':
            switch (type.name) {
                case 'date':
                    out.add('__date__');
                    break;
                case 'time':
                    out.add('__time__');
                    break;
                case 'datetime':
                    out.add('__datetime__');
                    break;
                case 'uuid':
                    out.add('__uuid__');
                    break;
                case 'unknown':
                case 'json':
                case 'object':
                    out.add('__any__');
                    break;
            }
            break;
        case 'ref':
            if (forInput && modelsWithInput?.has(type.name)) {
                out.add(`${type.name}Input`);
            } else {
                addModelRef(type.name, out, modelsWithInput);
            }
            break;
        case 'array':
            collectTypeRefs(type.item, out, modelsWithInput, forInput);
            break;
        case 'tuple':
            type.items.forEach(t => collectTypeRefs(t, out, modelsWithInput, forInput));
            break;
        case 'record':
            collectTypeRefs(type.key, out, modelsWithInput, forInput);
            collectTypeRefs(type.value, out, modelsWithInput, forInput);
            break;
        case 'union':
            type.members.forEach(m => collectTypeRefs(m, out, modelsWithInput, forInput));
            break;
        case 'discriminatedUnion':
            type.members.forEach(m => collectTypeRefs(m, out, modelsWithInput, forInput));
            break;
        case 'intersection':
            out.add('__any__');
            break;
        case 'lazy':
            collectTypeRefs(type.inner, out, modelsWithInput, forInput);
            break;
        case 'inlineObject':
            out.add('__any__');
            break;
    }
}
 
// ─── Naming helpers ───────────────────────────────────────────────────────
 
function deriveBaseName(file: string): string {
    const base =
        file
            .split('/')
            .pop()
            ?.replace(/\.(op\.)?ck$/, '') ?? 'Resource';
    return base
        .split('.')
        .map(s => s.charAt(0).toUpperCase() + s.slice(1))
        .join('');
}
 
export function deriveClientClassName(file: string): string {
    return `${deriveBaseName(file)}Client`;
}
 
export function deriveClientModuleName(file: string): string {
    const base =
        file
            .split('/')
            .pop()
            ?.replace(/\.(op\.)?ck$/, '') ?? 'client';
    const clean = base.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
    return `_client_${clean}`;
}
 
export function deriveClientPropertyName(file: string): string {
    const base = deriveBaseName(file);
    return base.charAt(0).toLowerCase() + base.slice(1);
}
 
function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {
    if (op.sdk) return toSnakeCase(op.sdk);
    if (op.name) return toSnakeCase(op.name);
    return inferMethodName(op.method, route.path);
}
 
function inferMethodName(method: string, path: string): string {
    const segments = path.split('/').filter(s => s.length > 0);
    const parts: string[] = [method.toLowerCase()];
 
    for (const seg of segments) {
        if (seg.startsWith('{')) {
            const paramName = seg.slice(1, -1);
            parts.push('by_' + toSnakeCase(paramName));
        } else {
            parts.push(toSnakeCase(seg.replace(/[.-]/g, '_')));
        }
    }
 
    return parts.join('_').replace(/_+/g, '_');
}
 
function toSnakeCase(s: string): string {
    return s
        .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
        .replace(/[^a-zA-Z0-9]/g, '_')
        .toLowerCase()
        .replace(/_+/g, '_')
        .replace(/^_|_$/g, '');
}
 
// ─── Shared base client content ───────────────────────────────────────────
 
export const BASE_CLIENT_PY = `# Auto-generated by contractkit-plugin-python-sdk. Do not edit manually.
from __future__ import annotations
 
import httpx
from typing import Any
 
 
class SdkError(Exception):
    def __init__(self, status: int, status_text: str, body: Any):
        super().__init__(f"{status} {status_text}")
        self.status = status
        self.status_text = status_text
        self.body = body
 
 
class BaseClient:
    def __init__(self, base_url: str, headers: dict[str, str] | None = None):
        self._base_url = base_url.rstrip("/")
        self._headers = headers or {}
        self._http = httpx.AsyncClient()
 
    async def _fetch(
        self,
        path: str,
        *,
        method: str,
        body: Any = None,
        params: dict | None = None,
        extra_headers: dict | None = None,
        content_type: str | None = None,
        body_kind: str = "json",
        response_kind: str = "json",
    ) -> Any:
        result, _ = await self._fetch_with_headers(
            path,
            method=method,
            body=body,
            params=params,
            extra_headers=extra_headers,
            content_type=content_type,
            body_kind=body_kind,
            response_kind=response_kind,
        )
        return result
 
    async def _fetch_with_headers(
        self,
        path: str,
        *,
        method: str,
        body: Any = None,
        params: dict | None = None,
        extra_headers: dict | None = None,
        content_type: str | None = None,
        body_kind: str = "json",
        response_kind: str = "json",
    ) -> tuple[Any, dict[str, str]]:
        headers = {**self._headers, **(extra_headers or {})}
        if body is not None:
            headers["Content-Type"] = content_type or "application/json"
        # body_kind controls how httpx serializes the request body:
        #   "json"   — body is a JSON-serializable object, sent via httpx's json= kwarg
        #   "text"/"binary" — body is a raw str/bytes payload, sent via content= unchanged
        request_kwargs: dict[str, Any] = {"method": method, "url": f"{self._base_url}{path}", "params": params, "headers": headers}
        if body is not None:
            if body_kind == "json":
                request_kwargs["json"] = body
            else:
                request_kwargs["content"] = body
        response = await self._http.request(**request_kwargs)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise SdkError(response.status_code, response.reason_phrase, error_body)
        # HTTP headers are case-insensitive — normalize to lowercase keys for stable lookup.
        response_headers = {k.lower(): v for k, v in response.headers.items()}
        if response.status_code == 204 or not response.content:
            return None, response_headers
        if response_kind == "text":
            return response.text, response_headers
        if response_kind == "binary":
            return response.content, response_headers
        return response.json(), response_headers
`;