All files / src codegen-markdown.ts

86.95% Statements 380/437
72.99% Branches 200/274
94.87% Functions 37/39
89.14% Lines 353/396

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 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867                                        77x   71x                             8x       1x           1x                     71x         54x     15x       1x       1x                                                                         97x 97x 97x 97x   97x 97x     97x 97x 97x     97x 97x   97x 90x 90x   90x 66x 66x 66x 68x 10x 10x 10x   68x 75x 75x   68x 10x 10x   68x       90x 32x 32x 32x 32x 2x 2x 2x   32x 37x   32x 2x 2x   32x       90x 90x       97x 66x 66x   66x 68x 10x 10x     68x 68x 75x 7x 7x   75x 75x 75x           97x 32x 32x   32x 32x 2x 2x     32x 37x 37x         97x           97x 97x 35x 40x     97x               3x 3x 3x   3x 3x                                                       97x 97x   97x 73x 73x 74x 83x 83x 75x 75x 12x 12x 12x   63x           97x   97x 58x     97x 10x     97x                 97x     69x 69x 73x 18x         69x 69x 10x 12x 12x 12x 15x 12x         69x 69x 19x 19x 1x 1x 1x         69x       97x 97x   97x 35x 35x 40x 37x 2x 2x 2x   35x         97x   97x 30x     97x 2x     97x                             14x 14x   14x 14x     14x 6x     8x                         150x 14x       136x 2x   2x 2x       316x 134x 134x 150x     1x                   1x                           75x 75x 75x 75x 75x 75x 75x     75x 75x     75x 75x 4x 4x 4x       75x 75x     75x 75x 75x 75x   75x                   75x     75x 75x 13x 13x 13x 13x       75x 7x 7x 7x   7x 6x 3x 3x     3x     4x 4x           75x 22x 22x   22x 22x 22x   22x 10x 10x 12x   2x 2x 2x 2x           2x       10x 10x     22x 1x 2x 2x 2x   1x 1x 1x 1x 2x 1x         75x                           75x     75x 8x 8x 8x                     75x 7x 7x 10x                     75x                           75x 5x 5x 3x 3x 1x     75x       13x 13x 13x 13x 18x 18x 18x   13x                   5x 5x 5x   5x 9x   9x 9x 9x 9x 9x 9x 9x   9x 9x   5x                 14x 12x   2x 1x   1x 2x 1x 2x 1x                 37x 37x   37x 37x   37x         37x 1x 1x     37x 3x 2x 2x       37x 1x 1x 1x 1x     36x 36x 36x 36x   36x 45x 45x 45x 45x 45x 45x 45x 45x   45x 45x     36x     36x                         17x 13x   5x   2x 2x 3x                   3x 3x 1x             2x 1x 1x 1x                 1x   1x 1x 2x 2x   1x             54x         147x       130x       40x         75x 172x 74x   74x 98x 9x 9x   89x 89x 89x         74x    
import {
    ContractRootNode,
    OpRootNode,
    OpRouteNode,
    OpOperationNode,
    ContractTypeNode,
    FieldNode,
    ModelNode,
    ParamSource,
    HttpMethod,
    resolveModifiers,
    resolveSecurity,
    SECURITY_NONE,
    collectPublicTypeNames,
    collectTypeRefs,
} from '@contractkit/core';
 
// ─── Local TypeScript type rendering ─────────────────────────────────────
 
function renderTsType(type: ContractTypeNode): string {
    switch (type.kind) {
        case 'scalar':
            return renderTsScalar(type.name);
        case 'array': {
            const inner = renderTsType(type.item);
            const needsParens =
                type.item.kind === 'union' ||
                type.item.kind === 'discriminatedUnion' ||
                type.item.kind === 'intersection' ||
                type.item.kind === 'enum';
            return needsParens ? `(${inner})[]` : `${inner}[]`;
        }
        case 'tuple':
            return `[${type.items.map(renderTsType).join(', ')}]`;
        case 'record':
            return `Record<${renderTsType(type.key)}, ${renderTsType(type.value)}>`;
        case 'enum':
            return type.values.map(v => `'${v}'`).join(' | ');
        case 'literal':
            return typeof type.value === 'string' ? `'${type.value}'` : String(type.value);
        case 'union':
            return type.members.map(renderTsType).join(' | ');
        case 'discriminatedUnion':
            return type.members.map(renderTsType).join(' | ');
        case 'intersection':
            return type.members.map(renderTsType).join(' & ');
        case 'ref':
            return type.name;
        case 'lazy':
            return renderTsType(type.inner);
        case 'inlineObject':
            return renderTsInlineObject(type.fields);
        default:
            return 'unknown';
    }
}
 
function renderTsScalar(name: string): string {
    switch (name) {
        case 'string':
        case 'email':
        case 'url':
        case 'uuid':
            return 'string';
        case 'number':
        case 'int':
            return 'number';
        case 'bigint':
            return 'bigint';
        case 'boolean':
            return 'boolean';
        case 'date':
        case 'datetime':
        case 'duration':
            return 'string';
        case 'null':
            return 'null';
        case 'unknown':
            return 'unknown';
        case 'object':
            return 'Record<string, unknown>';
        case 'binary':
            return 'Blob';
        case 'json':
            return 'JsonValue';
        default:
            return 'unknown';
    }
}
 
function renderTsInlineObject(fields: FieldNode[]): string {
    const entries = fields.map(f => {
        const opt = f.optional ? '?' : '';
        return `${f.name}${opt}: ${renderTsType(f.type)}`;
    });
    return `{ ${entries.join('; ')} }`;
}
 
// ─── Public entry point ────────────────────────────────────────────────────
 
export interface MarkdownCodegenContext {
    contractRoots: ContractRootNode[];
    opRoots: OpRootNode[];
    /**
     * Whether to document operations marked `internal`. Defaults to `false` — internal ops
     * are omitted from the rendered reference. Set to `true` for an internal-use doc.
     */
    includeInternal?: boolean;
}
 
export function generateMarkdown(ctx: MarkdownCodegenContext): string {
    const { contractRoots, opRoots } = ctx;
    const includeInternal = ctx.includeInternal ?? false;
    const modelIndex = buildModelIndex(contractRoots);
    const lines: string[] = [];
 
    lines.push('# API Reference');
    lines.push('');
 
    // ── Collect grouped data ─────────────────────────────────────
    const endpointGroups = groupEndpoints(opRoots, includeInternal);
    const publicModels = computePubliclyReachableModels(opRoots, contractRoots);
    const modelGroups = groupModels(contractRoots, publicModels);
 
    // ── Table of Contents ────────────────────────────────────────
    const hasEndpoints = endpointGroups.length > 0;
    const hasModels = modelGroups.length > 0;
 
    if (hasEndpoints || hasModels) {
        lines.push('## Table of Contents');
        lines.push('');
 
        if (hasEndpoints) {
            lines.push('**Endpoints**');
            lines.push('');
            for (const group of endpointGroups) {
                if (group.area) {
                    lines.push('<details>');
                    lines.push(`<summary><strong>${titleCase(group.area)}</strong> (${group.endpoints.length})</summary>`);
                    lines.push('');
                }
                for (const ep of group.endpoints) {
                    const title = deriveTitle(ep.op, ep.route);
                    lines.push(`- [${title}](#${anchor(title)})`);
                }
                if (group.area) {
                    lines.push('');
                    lines.push('</details>');
                }
                lines.push('');
            }
        }
 
        if (hasModels) {
            lines.push('**Models**');
            lines.push('');
            for (const group of modelGroups) {
                if (group.area) {
                    lines.push('<details>');
                    lines.push(`<summary><strong>${titleCase(group.area)}</strong> (${group.models.length})</summary>`);
                    lines.push('');
                }
                for (const model of group.models) {
                    lines.push(`- [${model.name}](#${anchor(model.name)})`);
                }
                if (group.area) {
                    lines.push('');
                    lines.push('</details>');
                }
                lines.push('');
            }
        }
 
        lines.push('---');
        lines.push('');
    }
 
    // ── Endpoints ──────────────────────────────────────────────
    if (hasEndpoints) {
        lines.push('## Endpoints');
        lines.push('');
 
        for (const group of endpointGroups) {
            if (group.area) {
                lines.push(`### ${titleCase(group.area)}`);
                lines.push('');
            }
 
            let first = true;
            for (const ep of group.endpoints) {
                if (!first) {
                    lines.push('---');
                    lines.push('');
                }
                first = false;
                lines.push(...renderEndpoint(ep.route, ep.op, group.area !== undefined, modelIndex));
                lines.push('');
            }
        }
    }
 
    // ── Models ─────────────────────────────────────────────────
    if (hasModels) {
        lines.push('## Models');
        lines.push('');
 
        for (const group of modelGroups) {
            if (group.area) {
                lines.push(`### ${titleCase(group.area)}`);
                lines.push('');
            }
 
            for (const model of group.models) {
                lines.push(...renderModel(model, group.area !== undefined));
                lines.push('');
            }
        }
    }
 
    return lines.join('\n');
}
 
// ─── Model index ──────────────────────────────────────────────────────────
 
function buildModelIndex(contractRoots: ContractRootNode[]): Map<string, ModelNode> {
    const index = new Map<string, ModelNode>();
    for (const root of contractRoots) {
        for (const model of root.models) {
            index.set(model.name, model);
        }
    }
    return index;
}
 
/**
 * Resolve a model's fields, following the `base` chain for inheritance.
 * Returns fields in order: base fields first, then own fields.
 */
function resolveModelFields(name: string, modelIndex: Map<string, ModelNode>): FieldNode[] | undefined {
    const model = modelIndex.get(name);
    Iif (!model) return undefined;
    Iif (model.type) return undefined; // type alias, no fields
 
    const ownFields = model.fields;
    Eif (!model.bases || model.bases.length === 0) return ownFields;
 
    const collected: FieldNode[] = [];
    for (const base of model.bases) {
        const baseFields = resolveModelFields(base, modelIndex);
        if (baseFields) collected.push(...baseFields);
    }
    return [...collected, ...ownFields];
}
 
// ─── Grouping ──────────────────────────────────────────────────────────────
 
interface EndpointEntry {
    route: OpRouteNode;
    op: OpOperationNode;
}
 
interface EndpointGroup {
    area: string | undefined;
    endpoints: EndpointEntry[];
}
 
interface ModelGroup {
    area: string | undefined;
    models: ModelNode[];
}
 
function groupEndpoints(opRoots: OpRootNode[], includeInternal = false): EndpointGroup[] {
    const grouped = new Map<string, EndpointEntry[]>();
    const ungrouped: EndpointEntry[] = [];
 
    for (const opRoot of opRoots) {
        const area = opRoot.meta?.area;
        for (const route of opRoot.routes) {
            for (const op of route.operations) {
                const mods = resolveModifiers(route, op);
                if (!includeInternal && mods.includes('internal')) continue;
                const entry: EndpointEntry = { route, op };
                if (area) {
                    const list = grouped.get(area) ?? [];
                    list.push(entry);
                    grouped.set(area, list);
                } else {
                    ungrouped.push(entry);
                }
            }
        }
    }
 
    const result: EndpointGroup[] = [];
 
    if (ungrouped.length > 0) {
        result.push({ area: undefined, endpoints: ungrouped });
    }
 
    for (const [area, endpoints] of grouped) {
        result.push({ area, endpoints });
    }
 
    return result;
}
 
/**
 * Returns the set of contract model names reachable from public (non-internal) operations,
 * transitively through model dependencies. Returns null when there are no .op files,
 * meaning all models should be shown.
 */
function computePubliclyReachableModels(opRoots: OpRootNode[], contractRoots: ContractRootNode[]): Set<string> | null {
    if (opRoots.length === 0) return null;
 
    // Seed with type names directly referenced by public ops
    const reachable = new Set<string>();
    for (const opRoot of opRoots) {
        for (const name of collectPublicTypeNames(opRoot)) {
            reachable.add(name);
        }
    }
 
    // Build model → dependency map
    const modelDeps = new Map<string, Set<string>>();
    for (const contractRoot of contractRoots) {
        for (const model of contractRoot.models) {
            const deps = new Set<string>();
            Iif (model.bases) for (const b of model.bases) deps.add(b);
            Iif (model.type) collectTypeRefs(model.type, deps);
            for (const field of model.fields) collectTypeRefs(field.type, deps);
            modelDeps.set(model.name, deps);
        }
    }
 
    // BFS expand through dependencies
    const frontier = [...reachable];
    while (frontier.length > 0) {
        const name = frontier.pop()!;
        for (const dep of modelDeps.get(name) ?? []) {
            Eif (!reachable.has(dep)) {
                reachable.add(dep);
                frontier.push(dep);
            }
        }
    }
 
    return reachable;
}
 
function groupModels(contractRoots: ContractRootNode[], publicModels: Set<string> | null): ModelGroup[] {
    const grouped = new Map<string, ModelNode[]>();
    const ungrouped: ModelNode[] = [];
 
    for (const contractRoot of contractRoots) {
        const area = contractRoot.meta?.area;
        for (const model of contractRoot.models) {
            if (publicModels !== null && !publicModels.has(model.name)) continue;
            if (area) {
                const list = grouped.get(area) ?? [];
                list.push(model);
                grouped.set(area, list);
            } else {
                ungrouped.push(model);
            }
        }
    }
 
    const result: ModelGroup[] = [];
 
    if (ungrouped.length > 0) {
        result.push({ area: undefined, models: ungrouped });
    }
 
    for (const [area, models] of grouped) {
        result.push({ area, models });
    }
 
    return result;
}
 
// ─── Title derivation ─────────────────────────────────────────────────────
 
/**
 * Normalize verb to imperative mood.
 * "Creates a new account" → "Create a new account"
 * "Lists all accounts" → "List all accounts"
 * "Gets a ledger account" → "Get a ledger account"
 * "Finalizes a transaction" → "Finalize a transaction"
 *
 * Leaves words ending in 'ss' alone (e.g. "Process").
 */
function normalizeVerbTitle(title: string): string {
    const spaceIdx = title.indexOf(' ');
    Iif (spaceIdx === -1) return title;
 
    const firstWord = title.slice(0, spaceIdx);
    const rest = title.slice(spaceIdx);
 
    // Strip third-person 's' from verbs (but not from words ending in 'ss' like "Process")
    if (firstWord.length > 3 && firstWord.endsWith('s') && !firstWord.endsWith('ss')) {
        return firstWord.slice(0, -1) + rest;
    }
 
    return title;
}
 
/**
 * Derive a human-readable verb-based title for an endpoint.
 *
 * Priority:
 * 1. op.description (title-cased, normalized to imperative mood)
 * 2. Service method name (e.g. "LedgerService.createAccount" → "Create account")
 * 3. Fallback: method + path segments (e.g. "Get ledger accounts")
 */
function deriveTitle(op: OpOperationNode, route: OpRouteNode): string {
    // 1. Use explicit description
    if (op.description) {
        return normalizeVerbTitle(titleCase(op.description.trim()));
    }
 
    // 2. Derive from service method name
    if (op.service) {
        const methodPart = op.service.split('.').pop()!;
        // camelCase → space-separated, title-cased first word
        const words = methodPart.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
        return titleCase(words);
    }
 
    // 3. Fallback: method + path segments
    const segments = route.path.split('/').filter(s => s.length > 0 && !s.startsWith('{'));
    const pathWords = segments.join(' ').replace(/[.-]/g, ' ');
    const verb = METHOD_VERBS[op.method] ?? op.method.toUpperCase();
    return `${verb} ${pathWords}`;
}
 
const METHOD_VERBS: Record<HttpMethod, string> = {
    get: 'List',
    post: 'Create',
    put: 'Update',
    patch: 'Update',
    delete: 'Delete',
};
 
// ─── Endpoint rendering ────────────────────────────────────────────────────
 
const STATUS_TEXT: Record<number, string> = {
    200: 'OK',
    201: 'Created',
    204: 'No Content',
    400: 'Bad Request',
    401: 'Unauthorized',
    403: 'Forbidden',
    404: 'Not Found',
    409: 'Conflict',
    422: 'Unprocessable Entity',
    500: 'Internal Server Error',
};
 
function renderEndpoint(route: OpRouteNode, op: OpOperationNode, nested: boolean, modelIndex: Map<string, ModelNode>): string[] {
    const lines: string[] = [];
    const method = op.method.toUpperCase();
    const path = route.path;
    const title = deriveTitle(op, route);
    const methodName = deriveMethodName(op, route);
    const h = nested ? '####' : '###';
    const subH = nested ? '#####' : '####';
 
    // Title
    lines.push(`${h} ${title}`);
    lines.push('');
 
    // Deprecation notice
    const mods = resolveModifiers(route, op);
    if (mods.includes('deprecated')) {
        lines.push('> [!WARNING]');
        lines.push('> **Deprecated** — this endpoint is deprecated and may be removed in a future version.');
        lines.push('');
    }
 
    // Method badge + path (compact line)
    lines.push(`**\`${method}\`** \`${path}\``);
    lines.push('');
 
    // SDK method + security (GitHub admonition)
    lines.push('> [!NOTE]');
    lines.push(`> SDK method: \`${methodName}\``);
    const effectiveSecurity = resolveSecurity(route, op);
    Iif (effectiveSecurity === SECURITY_NONE) {
        lines.push('> Security: public');
    } else Iif (effectiveSecurity !== undefined) {
        const parts: string[] = [];
        if (effectiveSecurity.roles && effectiveSecurity.roles.length > 0) {
            parts.push(`roles: ${effectiveSecurity.roles.join(', ')}`);
        }
        if (op.signature) {
            parts.push(`signature: ${op.signature}`);
        }
        lines.push(`> Security: authenticated${parts.length > 0 ? ` (${parts.join('; ')})` : ''}`);
    }
    lines.push('');
 
    // Unified attributes table (path + query + headers merged)
    const attrs = collectAttributes(route, op, modelIndex);
    if (attrs.length > 0) {
        lines.push(`${subH} Attributes`);
        lines.push('');
        lines.push(...wrapCollapsible(`Attributes (${attrs.length})`, renderAttributesTable(attrs)));
        lines.push('');
    }
 
    // Request body — render one section per accepted content type
    if (op.request && op.request.bodies.length > 0) {
        for (const body of op.request.bodies) {
            lines.push(`${subH} Request body (\`${body.contentType}\`)`);
            lines.push('');
 
            if (body.bodyType.kind === 'inlineObject') {
                const writableFields = body.bodyType.fields.filter(f => f.visibility !== 'readonly');
                Eif (writableFields.length > 0) {
                    lines.push(
                        ...wrapCollapsible(`Attributes (${writableFields.length})`, renderFieldsTable(writableFields, { excludeReadonly: true })),
                    );
                    lines.push('');
                }
            } else {
                lines.push(typeProseLink(body.bodyType, 'Accepts'));
                lines.push('');
            }
        }
    }
 
    // Responses
    if (op.responses.length > 0) {
        lines.push(`${subH} Response`);
        lines.push('');
 
        for (const resp of op.responses) {
            const statusText = STATUS_TEXT[resp.statusCode] ?? '';
            const statusLabel = statusText ? `${resp.statusCode} ${statusText}` : `${resp.statusCode}`;
 
            if (!resp.bodyType) {
                lines.push(`\`${statusLabel}\``);
                lines.push('');
            } else if (resp.bodyType.kind === 'inlineObject') {
                // Inline objects — expand into field table
                lines.push(`\`${statusLabel}\``);
                lines.push('');
                Eif (resp.bodyType.fields.length > 0) {
                    lines.push(
                        ...wrapCollapsible(
                            `Attributes (${resp.bodyType.fields.length})`,
                            renderFieldsTable(resp.bodyType.fields, { excludeReadonly: false }),
                        ),
                    );
                    lines.push('');
                }
            } else {
                // Named type — reference it; the Models section has the full definition
                lines.push(`\`${statusLabel}\` — ${typeProseLink(resp.bodyType, 'Returns')}`);
                lines.push('');
            }
 
            if (resp.headers && resp.headers.length > 0) {
                const headerRows = resp.headers.map(h => {
                    const required = h.optional ? '' : ' *(required)*';
                    const desc = h.description ? escapeCell(h.description) : '';
                    return `| \`${h.name}\` | \`${escapeCell(renderTsType(h.type))}\`${required} | ${desc} |`;
                });
                lines.push('Response headers:');
                lines.push('');
                lines.push('| Header | Type | Description |');
                lines.push('| ------ | ---- | ----------- |');
                for (const r of headerRows) lines.push(r);
                lines.push('');
            }
        }
    }
 
    return lines;
}
 
// ─── Attributes collection ────────────────────────────────────────────────
 
interface AttributeEntry {
    name: string;
    type: ContractTypeNode;
    required: boolean;
    description: string;
    source: 'path' | 'query' | 'header';
}
 
function collectAttributes(route: OpRouteNode, op: OpOperationNode, modelIndex: Map<string, ModelNode>): AttributeEntry[] {
    const attrs: AttributeEntry[] = [];
 
    // Path parameters (always required, listed first)
    if (route.params) {
        const params = flattenParamSource(route.params, modelIndex);
        for (const p of params) {
            attrs.push({
                name: p.name,
                type: p.type,
                required: true,
                description: p.description ? `${p.description}. Path parameter.` : 'Path parameter.',
                source: 'path',
            });
        }
    }
 
    // Query parameters
    if (op.query) {
        const params = flattenParamSource(op.query, modelIndex);
        for (const p of params) {
            attrs.push({
                name: p.name,
                type: p.type,
                required: !p.optional,
                description: p.description ?? '',
                source: 'query',
            });
        }
    }
 
    // Header parameters
    Iif (op.headers) {
        const params = flattenParamSource(op.headers, modelIndex);
        for (const p of params) {
            attrs.push({
                name: p.name,
                type: p.type,
                required: !p.optional,
                description: p.description ?? '',
                source: 'header',
            });
        }
    }
 
    // Sort: path first, then required, then optional alphabetically
    attrs.sort((a, b) => {
        Iif (a.source === 'path' && b.source !== 'path') return -1;
        if (a.source !== 'path' && b.source === 'path') return 1;
        Iif (a.required && !b.required) return -1;
        if (!a.required && b.required) return 1;
        return a.name.localeCompare(b.name);
    });
 
    return attrs;
}
 
function renderAttributesTable(attrs: AttributeEntry[]): string[] {
    const lines: string[] = [];
    lines.push('| Attribute | Type | Required | Description |');
    lines.push('| --- | --- | --- | --- |');
    for (const attr of attrs) {
        const type = escapeCell(renderTsType(attr.type));
        const req = attr.required ? 'Yes' : 'No';
        lines.push(`| \`${attr.name}\` | \`${type}\` | ${req} | ${escapeCell(attr.description)} |`);
    }
    return lines;
}
 
// ─── Field / body helpers ─────────────────────────────────────────────────
 
interface FieldsTableOpts {
    excludeReadonly: boolean;
}
 
function renderFieldsTable(fields: FieldNode[], opts: FieldsTableOpts): string[] {
    const lines: string[] = [];
    lines.push('| Attribute | Type | Required | Description |');
    lines.push('| --- | --- | --- | --- |');
 
    for (const f of fields) {
        Iif (opts.excludeReadonly && f.visibility === 'readonly') continue;
 
        const type = escapeCell(renderTsType(f.type));
        const required = f.optional ? 'No' : 'Yes';
        const modifiers: string[] = [];
        if (f.visibility === 'readonly') modifiers.push('read-only');
        Iif (f.visibility === 'writeonly') modifiers.push('write-only');
        Iif (f.nullable) modifiers.push('nullable');
        Iif (f.default !== undefined) modifiers.push(`default: \`${f.default}\``);
 
        const desc = escapeCell([f.description, ...modifiers.map(m => `*${m}*`)].filter(Boolean).join('. '));
        lines.push(`| \`${f.name}\` | \`${type}\` | ${required} | ${desc} |`);
    }
    return lines;
}
 
/**
 * Generate prose-style reference text for a body type.
 * E.g. "Accepts a [CreateUser](#createuser) object."
 *      "Returns a list of [User](#user) objects."
 */
function typeProseLink(type: ContractTypeNode, verb: 'Accepts' | 'Returns'): string {
    if (type.kind === 'ref') {
        return `${verb} a [${type.name}](#${anchor(type.name)}) object.`;
    }
    if (type.kind === 'array' && type.item.kind === 'ref') {
        return `${verb} a list of [${type.item.name}](#${anchor(type.item.name)}) objects.`;
    }
    Eif (type.kind === 'union') {
        const allRefs = type.members.every(m => m.kind === 'ref');
        Eif (allRefs && type.members.length > 0) {
            const links = type.members.map(m => (m.kind === 'ref' ? `[${m.name}](#${anchor(m.name)})` : renderTsType(m)));
            return `${verb} a ${links.join(' or ')} object.`;
        }
    }
    return `${verb} \`${escapeCell(renderTsType(type))}\`.`;
}
 
// ─── Model rendering ──────────────────────────────────────────────────────
 
function renderModel(model: ModelNode, nested: boolean): string[] {
    const lines: string[] = [];
    const heading = nested ? '####' : '###';
 
    lines.push(`${heading} ${model.name}`);
    lines.push('');
 
    Iif (model.deprecated) {
        lines.push('> **Deprecated** — this type is deprecated and may be removed in a future version.');
        lines.push('');
    }
 
    if (model.description) {
        lines.push(`> ${model.description}`);
        lines.push('');
    }
 
    if (model.bases && model.bases.length > 0) {
        const links = model.bases.map(b => `[\`${b}\`](#${anchor(b)})`).join(', ');
        lines.push(`Extends ${links}`);
        lines.push('');
    }
 
    // Type alias (no fields)
    if (model.type) {
        lines.push(`\`\`\`typescript`);
        lines.push(`type ${model.name} = ${renderTsType(model.type)}`);
        lines.push(`\`\`\``);
        return lines;
    }
 
    Eif (model.fields.length > 0) {
        const tableLines: string[] = [];
        tableLines.push('| Attribute | Type | Required | Description |');
        tableLines.push('| --- | --- | --- | --- |');
 
        for (const field of model.fields) {
            const type = escapeCell(renderTsType(field.type));
            const required = field.optional ? 'No' : 'Yes';
            const modifiers: string[] = [];
            Iif (field.deprecated) modifiers.push('deprecated');
            if (field.visibility === 'readonly') modifiers.push('read-only');
            if (field.visibility === 'writeonly') modifiers.push('write-only');
            if (field.nullable) modifiers.push('nullable');
            if (field.default !== undefined) modifiers.push(`default: \`${field.default}\``);
 
            const desc = escapeCell([field.description, ...modifiers.map(m => `*${m}*`)].filter(Boolean).join('. '));
            tableLines.push(`| \`${field.name}\` | \`${type}\` | ${required} | ${desc} |`);
        }
 
        lines.push(...wrapCollapsible(`Attributes (${model.fields.length})`, tableLines));
    }
 
    return lines;
}
 
// ─── Helpers ──────────────────────────────────────────────────────────────
 
interface FlatParam {
    name: string;
    type: ContractTypeNode;
    optional: boolean;
    description?: string;
}
 
function flattenParamSource(source: ParamSource, modelIndex: Map<string, ModelNode>): FlatParam[] {
    if (source.kind === 'params') {
        return source.nodes.map(p => ({ name: p.name, type: p.type, optional: p.optional }));
    }
    if (source.kind === 'ref') {
        // String reference — resolve from model index
        const fields = resolveModelFields(source.name, modelIndex);
        Eif (fields) {
            return fields.map(f => ({
                name: f.name,
                type: f.type,
                optional: f.optional,
                description: f.description,
            }));
        }
        return [];
    }
    // ContractTypeNode
    const node = source.node;
    if (node.kind === 'inlineObject') {
        return node.fields.map(f => ({
            name: f.name,
            type: f.type,
            optional: f.optional,
            description: f.description,
        }));
    }
    if (node.kind === 'ref') {
        const fields = resolveModelFields(node.name, modelIndex);
        Eif (fields) {
            return fields.map(f => ({
                name: f.name,
                type: f.type,
                optional: f.optional,
                description: f.description,
            }));
        }
        return [];
    }
    Eif (node.kind === 'intersection') {
        // Flatten all members of the intersection
        const result: FlatParam[] = [];
        for (const member of node.members) {
            const memberParams = flattenParamSource({ kind: 'type', node: member }, modelIndex);
            result.push(...memberParams);
        }
        return result;
    }
    return [];
}
 
/** Wrap lines in a collapsible <details> block (collapsed by default). */
function wrapCollapsible(summary: string, tableLines: string[]): string[] {
    return ['<details>', `<summary>${summary}</summary>`, '', ...tableLines, '', '</details>'];
}
 
/** Escape pipe characters inside markdown table cells. */
function escapeCell(s: string): string {
    return s.replace(/\|/g, '\\|');
}
 
function anchor(name: string): string {
    return name.toLowerCase().replace(/[^a-z0-9]+/g, '-');
}
 
function titleCase(s: string): string {
    return s.charAt(0).toUpperCase() + s.slice(1);
}
 
/** Derive SDK method name — mirrors codegen-sdk.ts logic. */
function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {
    if (op.sdk) return op.sdk;
    const segments = route.path.split('/').filter(s => s.length > 0);
    const parts: string[] = [op.method.toLowerCase()];
 
    for (const seg of segments) {
        if (seg.startsWith('{')) {
            const paramName = seg.slice(1, -1);
            parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));
        } else {
            const segParts = seg.split(/[.-]/).filter(Boolean);
            for (const sp of segParts) {
                parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));
            }
        }
    }
 
    return parts.join('');
}