All files / src codegen-bruno.ts

87.31% Statements 289/331
76.72% Branches 211/275
92.15% Functions 47/51
88.58% Lines 256/289

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                                            1x                                                                                                           93x   93x 93x 93x 93x 93x   93x 93x 94x           93x 4x 4x 4x 4x       93x 95x 95x 95x   95x   95x 95x 95x   95x 4x 4x       95x 95x 98x 102x 101x     95x   95x 95x 101x 101x 101x 101x     101x 5x   101x 101x       387x 95x         95x         5x 5x 7x 1x         4x           20x               13x 13x 13x   13x   7x                             10x 10x 3x   7x 7x           93x 93x 7x 7x 7x   93x 93x             93x 4x         90x 90x 7x   90x       94x 94x 104x 104x 104x   94x 94x       4x       99x                         101x   101x 101x 101x 101x 101x 101x 101x 101x       101x           101x 15x   101x   101x 20x 20x 29x 29x 29x 29x         101x 4x 4x 4x 4x 6x 6x 6x           101x 7x 7x 1x 1x   6x         101x 19x           57x   19x 19x 1x 1x 18x       18x 18x 18x 18x 60x           101x 101x 101x 101x 10x 10x 10x 10x 10x     10x 10x 1x 1x 1x         101x 101x 3x 3x 3x 8x       101x 101x         101x 101x         101x 101x 101x 101x 101x 1x 1x 2x 2x 2x   1x   101x             7x 7x 5x   2x 1x   1x 1x 1x             6x 2x 1x             93x 93x 8x 9x     93x         9x 9x 1x 1x 1x     9x                           12x 13x   5x 5x 5x 3x 7x 6x     2x 2x                     14x 6x                         35x 35x 25x 24x 24x 24x 5x 5x   19x   5x   1x           6x       1x           1x   5x           5x   1x   1x           1x   1x   1x                                   38x   17x   7x   3x       2x       2x   1x           1x   1x             1x       1x                       9x 9x   5x 5x         10x               5x         15x 15x 29x 26x 6x 20x 19x     15x             101x         14x       14x         101x             101x         101x         92x               394x 115x   279x    
import type {
    OpRootNode,
    OpRouteNode,
    OpOperationNode,
    OpResponseNode,
    ParamSource,
    ContractTypeNode,
    ContractRootNode,
    ModelNode,
    FieldNode,
} from '@contractkit/core';
import { resolveSecurity, resolveModifiers, SECURITY_NONE } from '@contractkit/core';
import { basename } from 'path';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
 
/** A single file produced by the Bruno codegen — a relative output path and its YAML content. */
export interface OpenCollectionFile {
    relativePath: string;
    content: string;
}
 
/** Manifest filename — tracks which files this plugin previously generated so subsequent runs can clean up only those, leaving any user-added files alone. */
export const MANIFEST_FILENAME = '.contractkit-bruno-manifest.json';
 
/** Subset of a security scheme sufficient for Bruno auth generation (non-HMAC). */
export interface BrunoSecurityScheme {
    type: string; // "http" | "apiKey" | "oauth2" | "openIdConnect"
    scheme?: string; // "bearer" | "basic" (when type === "http")
    name?: string; // header/query param name (when type === "apiKey")
    in?: string; // "header" | "query" (when type === "apiKey")
}
 
/** Auth configuration passed to the Bruno codegen; drives collection-level auth and per-operation auth blocks. */
export interface BrunoAuthOptions {
    /** Name of the default scheme (from config.security.default) */
    defaultScheme?: string;
    /** Scheme definitions keyed by name (non-HMAC only) */
    schemes?: Record<string, BrunoSecurityScheme>;
}
 
/** Options controlling what {@link generateOpenCollection} emits. */
export interface OpenCollectionOptions {
    collectionName: string;
    contractRoots?: ContractRootNode[];
    auth?: BrunoAuthOptions;
    /**
     * When true, emit Bruno faker template strings (e.g. `{{$randomUUID}}`,
     * `{{$randomEmail}}`) for compatible scalar types so each send produces
     * fresh data. When false (default), use deterministic placeholders.
     */
    randomExamples?: boolean;
    /**
     * Whether to generate request files for operations marked `internal`. Defaults to
     * `true` — Bruno collections are typically used by the team that owns the API and
     * benefit from full coverage. Set to `false` to omit internal ops.
     */
    includeInternal?: boolean;
    /**
     * Map of environment name → variables. Each entry produces a
     * `environments/<name>.yml` file with the variables in declaration order.
     * Values are coerced to strings.
     *
     * When omitted, a default `environments/local.yml` is emitted with
     * `baseUrl=http://localhost:3000` plus any auth env-var placeholders the
     * default scheme requires. When provided, the default is replaced entirely
     * — auth vars are not auto-injected, so include them explicitly if needed.
     */
    environments?: Record<string, Record<string, unknown>>;
}
 
/**
 * Generates an OpenCollection (https://spec.opencollection.com/) API collection
 * from a set of operation roots. Produces opencollection.yml, an environment
 * file, and one .yml request file per operation.
 */
export function generateOpenCollection(roots: OpRootNode[], options: OpenCollectionOptions): OpenCollectionFile[] {
    const files: OpenCollectionFile[] = [];
 
    const modelMap = buildModelMap(options.contractRoots ?? []);
    const authOpts = options.auth;
    const defaultScheme = authOpts?.defaultScheme ? authOpts.schemes?.[authOpts.defaultScheme] : undefined;
    const randomExamples = options.randomExamples ?? false;
    const includeInternal = options.includeInternal ?? true;
 
    files.push({ relativePath: 'opencollection.yml', content: generateCollectionRoot(options.collectionName, defaultScheme) });
    for (const envFile of generateEnvFiles(options.environments, defaultScheme)) {
        files.push(envFile);
    }
    // Manifest is appended at the end so it lists every generated path including itself.
 
    // Roots are sorted by their top-level folder display name (then by subarea) so the
    // emitted `seq:` numbers — which drive Bruno's UI ordering — line up alphabetically.
    const sortedRoots = [...roots].sort((a, b) => {
        const aArea = a.meta['area'] ?? deriveFolderName(a.file);
        const bArea = b.meta['area'] ?? deriveFolderName(b.file);
        const cmp = aArea.localeCompare(bArea);
        Eif (cmp !== 0) return cmp;
        return (a.meta['subarea'] ?? '').localeCompare(b.meta['subarea'] ?? '');
    });
 
    for (let rootIdx = 0; rootIdx < sortedRoots.length; rootIdx++) {
        const root = sortedRoots[rootIdx]!;
        const folder = root.meta['area'] ? slugifyName(root.meta['area']) : deriveFolderName(root.file);
        const displayName = (root.meta['area'] ?? folder).charAt(0).toUpperCase() + (root.meta['area'] ?? folder).slice(1);
 
        files.push({ relativePath: `${folder}/folder.yml`, content: generateFolderFile(displayName, rootIdx + 1) });
 
        const subarea = root.meta['subarea'];
        const subareaSlug = subarea ? slugifyName(subarea) : undefined;
        const requestDir = subareaSlug ? `${folder}/${subareaSlug}` : folder;
 
        if (subareaSlug) {
            const subareaDisplayName = subarea!.charAt(0).toUpperCase() + subarea!.slice(1);
            files.push({ relativePath: `${requestDir}/folder.yml`, content: generateFolderFile(subareaDisplayName, 1) });
        }
 
        // Flatten and alphabetize within this folder before assigning `seq:`.
        const requests: Array<{ route: typeof root.routes[number]; op: typeof root.routes[number]['operations'][number]; requestName: string }> = [];
        for (const route of root.routes) {
            for (const op of route.operations) {
                if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
                requests.push({ route, op, requestName: op.name ?? route.path });
            }
        }
        requests.sort((a, b) => a.requestName.localeCompare(b.requestName));
 
        let seq = 1;
        for (const { route, op, requestName } of requests) {
            const fileName = op.name ? `${slugifyName(op.name)}.yml` : `${op.method}-${sanitizePath(route.path)}.yml`;
            let content = generateRequestFile(route, op, requestName, seq, modelMap, root, defaultScheme, randomExamples);
            const brunoExt = op.pluginExtensions?.['bruno'];
            const pluginOverride = brunoExt && typeof brunoExt === 'object' && !Array.isArray(brunoExt)
                ? brunoExt['template']
                : undefined;
            if (typeof pluginOverride === 'string') {
                content = mergePluginFile(content, pluginOverride);
            }
            files.push({ relativePath: `${requestDir}/${fileName}`, content });
            seq++;
        }
    }
 
    const trackedPaths = [...files.map(f => f.relativePath), MANIFEST_FILENAME].sort();
    files.push({
        relativePath: MANIFEST_FILENAME,
        content: JSON.stringify({ files: trackedPaths }, null, 2) + '\n',
    });
 
    return files;
}
 
/** Parse a previously-written manifest. Returns the list of relative paths to clean up. Returns [] if missing or unreadable so a stale/garbled manifest never blocks regeneration. */
export function parseManifest(content: string): string[] {
    try {
        const parsed = JSON.parse(content);
        if (Array.isArray(parsed?.files) && parsed.files.every((f: unknown) => typeof f === 'string')) {
            return parsed.files as string[];
        }
    } catch {
        // fall through
    }
    return [];
}
 
// ─── Plugin file merge ─────────────────────────────────────────────────────
 
function deepMerge(base: unknown, override: unknown): unknown {
    if (
        override !== null &&
        typeof override === 'object' &&
        !Array.isArray(override) &&
        base !== null &&
        typeof base === 'object' &&
        !Array.isArray(base)
    ) {
        const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };
        for (const [key, val] of Object.entries(override as Record<string, unknown>)) {
            result[key] = deepMerge(result[key], val);
        }
        return result;
    }
    return override;
}
 
/**
 * Deep-merges a YAML override string into a generated YAML string.
 *
 * Objects are merged recursively; arrays and scalars in the override replace the
 * generated value entirely. If `pluginFileContent` is not a YAML mapping (e.g. it
 * is a scalar or a list), the generated content is returned unchanged.
 *
 * @param generatedYaml - The YAML string produced by the Bruno codegen.
 * @param pluginFileContent - The YAML override string to merge in.
 * @returns The merged YAML string, or `generatedYaml` if the override is not a mapping.
 */
export function mergePluginFile(generatedYaml: string, pluginFileContent: string): string {
    const overrideParsed = parseYaml(pluginFileContent);
    if (overrideParsed === null || typeof overrideParsed !== 'object' || Array.isArray(overrideParsed)) {
        return generatedYaml;
    }
    const merged = deepMerge(parseYaml(generatedYaml), overrideParsed);
    return stringifyYaml(merged, { lineWidth: 0 });
}
 
// ─── File generators ───────────────────────────────────────────────────────
 
function generateCollectionRoot(name: string, scheme?: BrunoSecurityScheme): string {
    const lines = [`opencollection: "1.0.0"`, `info:`, `  name: ${yamlString(name)}`];
    if (scheme) {
        lines.push(``);
        lines.push(`request:`);
        lines.push(...renderAuthBlock(scheme, '  '));
    }
    lines.push(``);
    return lines.join('\n');
}
 
function generateEnvFiles(
    environments: Record<string, Record<string, unknown>> | undefined,
    scheme: BrunoSecurityScheme | undefined,
): OpenCollectionFile[] {
    if (environments && Object.keys(environments).length > 0) {
        return Object.entries(environments).map(([name, variables]) => ({
            relativePath: `environments/${name}.yml`,
            content: renderEnvFile(displayNameFor(name), variables),
        }));
    }
    const defaultVars: Record<string, string> = { baseUrl: 'http://localhost:3000' };
    if (scheme) {
        for (const varName of authEnvVarNames(scheme)) defaultVars[varName] = '';
    }
    return [{ relativePath: 'environments/local.yml', content: renderEnvFile('Local', defaultVars) }];
}
 
function renderEnvFile(name: string, variables: Record<string, unknown>): string {
    const lines = [`name: ${name}`, `variables:`];
    for (const [key, value] of Object.entries(variables)) {
        const escaped = String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
        lines.push(`  - name: ${key}`);
        lines.push(`    value: "${escaped}"`);
    }
    lines.push(``);
    return lines.join('\n');
}
 
function displayNameFor(envKey: string): string {
    return envKey.charAt(0).toUpperCase() + envKey.slice(1);
}
 
function generateFolderFile(name: string, seq: number): string {
    return [`info:`, `  name: ${yamlString(name)}`, `  type: folder`, `  seq: ${seq}`, ``].join('\n');
}
 
function generateRequestFile(
    route: OpRouteNode,
    op: OpOperationNode,
    name: string,
    seq: number,
    modelMap: Map<string, ModelNode>,
    root?: OpRootNode,
    defaultScheme?: BrunoSecurityScheme,
    randomExamples = false,
): string {
    const lines: string[] = [];
 
    lines.push(`info:`);
    lines.push(`  name: ${yamlString(name)}`);
    lines.push(`  type: http`);
    lines.push(`  seq: ${seq}`);
    lines.push(``);
    lines.push(`http:`);
    lines.push(`  method: ${op.method.toUpperCase()}`);
    lines.push(`  url: ${yamlString(`{{baseUrl}}${openCollectionPath(route.path)}`)}`);
 
    // Params — flat array with type: "path" | "query". Optional query params are
    // emitted with disabled: true so users opt in before sending.
    const pathParams: Array<ParamEntry & { kind: 'path' | 'query' }> = extractPathParamNames(route.path).map(n => ({
        name: n,
        type: findParamType(route.params, n, modelMap),
        optional: false,
        kind: 'path' as const,
    }));
    const queryParams: Array<ParamEntry & { kind: 'path' | 'query' }> = op.query
        ? expandParamSource(op.query, modelMap).map(e => ({ ...e, kind: 'query' as const }))
        : [];
    const allParams = [...pathParams, ...queryParams];
 
    if (allParams.length > 0) {
        lines.push(`  params:`);
        for (const p of allParams) {
            lines.push(`    - name: ${p.name}`);
            lines.push(`      value: ${paramExampleValue(p.type, p.default, randomExamples)}`);
            lines.push(`      type: ${p.kind}`);
            if (p.optional && p.kind === 'query') lines.push(`      disabled: true`);
        }
    }
 
    // Headers
    if (op.headers) {
        const headerEntries = expandParamSource(op.headers, modelMap);
        Eif (headerEntries.length > 0) {
            lines.push(`  headers:`);
            for (const h of headerEntries) {
                lines.push(`    - name: ${h.name}`);
                lines.push(`      value: ${paramExampleValue(h.type, h.default, randomExamples)}`);
                if (h.optional) lines.push(`      disabled: true`);
            }
        }
    }
 
    // Auth — inside http block; inherit collection default unless this op is explicitly public
    if (defaultScheme) {
        const security = root ? resolveSecurity(route, op, root) : (op.security ?? route.security);
        if (security === SECURITY_NONE) {
            lines.push(`  auth:`);
            lines.push(`    type: none`);
        } else {
            lines.push(`  auth: inherit`);
        }
    }
 
    // Body — Bruno supports a single body per request, so prefer JSON, then form-urlencoded, then multipart.
    if (op.request && op.request.bodies.length > 0) {
        const preferredOrder: Array<(typeof op.request.bodies)[number]['contentType']> = [
            'application/json',
            'application/x-www-form-urlencoded',
            'multipart/form-data',
        ];
        const primary =
            preferredOrder.map(ct => op.request!.bodies.find(b => b.contentType === ct)).find(b => b !== undefined) ?? op.request.bodies[0]!;
 
        lines.push(`  body:`);
        if (primary.contentType === 'multipart/form-data') {
            lines.push(`    type: multipart-form`);
            lines.push(`    data: []`);
        } else Iif (primary.contentType === 'application/x-www-form-urlencoded') {
            lines.push(`    type: form-urlencoded`);
            lines.push(`    data: []`);
        } else {
            const json = JSON.stringify(typeToExampleValue(primary.bodyType, modelMap, randomExamples), null, 2);
            lines.push(`    type: json`);
            lines.push(`    data: |`);
            for (const jsonLine of json.split('\n')) {
                lines.push(`      ${jsonLine}`);
            }
        }
    }
 
    // runtime.assertions — auto-generate a status-code check and presence checks for required response headers.
    const expectedStatus = pickAssertionStatus(op.responses);
    const assertedResponse = op.responses.find(r => r.statusCode === expectedStatus);
    const requiredHeaders = (assertedResponse?.headers ?? []).filter(h => !h.optional);
    if (expectedStatus !== undefined) {
        lines.push(``);
        lines.push(`runtime:`);
        lines.push(`  assertions:`);
        lines.push(`    - expression: res.status`);
        lines.push(`      operator: eq`);
        // Always quote — the OpenCollection schema types `value` as a string,
        // so we must keep "200" from being parsed as YAML number 200.
        lines.push(`      value: "${expectedStatus}"`);
        for (const h of requiredHeaders) {
            lines.push(`    - expression: res.headers["${h.name.toLowerCase()}"]`);
            lines.push(`      operator: isDefined`);
            lines.push(`      value: ""`);
        }
    }
 
    // docs — combine route- and operation-level descriptions plus the declared response-header summary.
    const docs = buildRequestDocs(route, op, assertedResponse);
    if (docs) {
        lines.push(``);
        lines.push(`docs: |-`);
        for (const docLine of docs.split('\n')) {
            lines.push(`  ${docLine}`);
        }
    }
 
    lines.push(``);
    return lines.join('\n');
}
 
/** Pick the response whose status code we'll assert against. Prefers the first declared 2xx; otherwise falls back to the first declared response. Returns undefined if no responses are declared. */
function pickAssertionStatus(responses: OpResponseNode[]): number | undefined {
    const success = responses.find(r => r.statusCode >= 200 && r.statusCode < 300);
    return success?.statusCode ?? responses[0]?.statusCode;
}
 
/** Build a markdown docs block from route- and operation-level descriptions, plus declared response-header summary. */
function buildRequestDocs(route: OpRouteNode, op: OpOperationNode, assertedResponse?: OpResponseNode): string | undefined {
    const parts: string[] = [];
    if (route.description) parts.push(route.description.trim());
    if (op.description) parts.push(op.description.trim());
    const headers = assertedResponse?.headers ?? [];
    if (headers.length > 0) {
        const lines = ['**Response headers**', ''];
        for (const h of headers) {
            const tag = h.optional ? 'optional' : 'required';
            const desc = h.description ? ` — ${h.description}` : '';
            lines.push(`- \`${h.name}\` (${tag})${desc}`);
        }
        parts.push(lines.join('\n'));
    }
    return parts.length > 0 ? parts.join('\n\n') : undefined;
}
 
// ─── Auth helpers ──────────────────────────────────────────────────────────
 
/** Generate the YAML lines for an auth block (flat, per spec), indented by `indent`. */
function renderAuthBlock(scheme: BrunoSecurityScheme, indent: string): string[] {
    const i = indent;
    if (scheme.type === 'http' && scheme.scheme === 'bearer') {
        return [`${i}auth:`, `${i}  type: bearer`, `${i}  token: "{{token}}"`];
    }
    if (scheme.type === 'http' && scheme.scheme === 'basic') {
        return [`${i}auth:`, `${i}  type: basic`, `${i}  username: "{{username}}"`, `${i}  password: "{{password}}"`];
    }
    Eif (scheme.type === 'apiKey' && scheme.in === 'header') {
        const headerName = scheme.name ?? 'X-Api-Key';
        return [`${i}auth:`, `${i}  type: apikey`, `${i}  key: ${headerName}`, `${i}  value: "{{apiKey}}"`, `${i}  placement: header`];
    }
    return [];
}
 
/** Return the environment variable names needed for a given auth scheme. */
function authEnvVarNames(scheme: BrunoSecurityScheme): string[] {
    if (scheme.type === 'http' && scheme.scheme === 'bearer') return ['token'];
    if (scheme.type === 'http' && scheme.scheme === 'basic') return ['username', 'password'];
    Eif (scheme.type === 'apiKey') return ['apiKey'];
    return [];
}
 
// ─── Model registry ────────────────────────────────────────────────────────
 
function buildModelMap(contractRoots: ContractRootNode[]): Map<string, ModelNode> {
    const map = new Map<string, ModelNode>();
    for (const root of contractRoots) {
        for (const model of root.models) {
            map.set(model.name, model);
        }
    }
    return map;
}
 
/** Resolve all fields for a model, including inherited base fields (bases first, in declaration order). */
function resolveModelFields(model: ModelNode, modelMap: Map<string, ModelNode>): FieldNode[] {
    const collected: FieldNode[] = [];
    if (model.bases) {
        for (const base of model.bases) {
            const baseModel = modelMap.get(base);
            Eif (baseModel) collected.push(...resolveModelFields(baseModel, modelMap));
        }
    }
    return [...collected, ...model.fields];
}
 
// ─── Param helpers ─────────────────────────────────────────────────────────
 
interface ParamEntry {
    name: string;
    type: ContractTypeNode | undefined;
    default?: string | number | boolean;
    optional: boolean;
}
 
/** Expand a ParamSource into a flat list of named entries with their types. */
function expandParamSource(source: ParamSource, modelMap: Map<string, ModelNode>): ParamEntry[] {
    if (source.kind === 'params') {
        return source.nodes.map(n => ({ name: n.name, type: n.type, default: n.default, optional: n.optional }));
    }
    Eif (source.kind === 'ref') {
        const model = modelMap.get(source.name);
        if (model) {
            return resolveModelFields(model, modelMap)
                .filter(f => f.visibility !== 'readonly')
                .map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));
        }
        // Fallback: single placeholder entry
        const name = source.name.charAt(0).toLowerCase() + source.name.slice(1);
        return [{ name, type: undefined, optional: false }];
    }
    // kind === 'type': if it's an inline object, expand its fields
    if (source.node.kind === 'inlineObject') {
        return source.node.fields.map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));
    }
    return [];
}
 
/** Look up a named path param's type from route.params. */
function findParamType(source: ParamSource | undefined, name: string, modelMap: Map<string, ModelNode>): ContractTypeNode | undefined {
    if (!source) return undefined;
    Eif (source.kind === 'params') return source.nodes.find(n => n.name === name)?.type;
    if (source.kind === 'ref') {
        const model = modelMap.get(source.name);
        if (model) return resolveModelFields(model, modelMap).find(f => f.name === name)?.type;
    }
    if (source.kind === 'type' && source.node.kind === 'inlineObject') {
        return source.node.fields.find(f => f.name === name)?.type;
    }
    return undefined;
}
 
/** Return a YAML-quoted example value string for a param, preferring a default value when provided. */
function paramExampleValue(type: ContractTypeNode | undefined, defaultValue?: string | number | boolean, randomExamples = false): string {
    Iif (defaultValue !== undefined) return `"${defaultValue}"`;
    if (!type) return '""';
    if (type.kind === 'enum') return type.values.length > 0 ? `"${type.values[0]}"` : '""';
    Iif (type.kind === 'literal') return `"${type.value}"`;
    Iif (type.kind !== 'scalar') return '""';
    if (randomExamples) {
        const random = randomScalarTemplate(type.name);
        Eif (random !== undefined) return `"${random}"`;
    }
    switch (type.name) {
        case 'uuid':
            return '"00000000-0000-0000-0000-000000000000"';
        case 'email':
            return '"user@example.com"';
        case 'url':
            return '"https://example.com"';
        case 'number':
        case 'int':
        case 'bigint':
            return '"0"';
        case 'boolean':
            return '"true"';
        case 'date':
            return '"2024-01-01"';
        case 'time':
            return '"00:00:00"';
        case 'datetime':
            return '"2024-01-01T00:00:00Z"';
        case 'duration':
            return '"PT1H"';
        default:
            return '""';
    }
}
 
/** Bruno faker template for a scalar type, or undefined when no clean equivalent exists (date, time, duration, raw string). */
function randomScalarTemplate(name: string): string | undefined {
    switch (name) {
        case 'uuid':
            return '{{$randomUUID}}';
        case 'email':
            return '{{$randomEmail}}';
        case 'url':
            return '{{$randomUrl}}';
        case 'number':
        case 'int':
        case 'bigint':
            return '{{$randomInt}}';
        case 'boolean':
            return '{{$randomBoolean}}';
        case 'datetime':
            return '{{$isoTimestamp}}';
        default:
            return undefined;
    }
}
 
// ─── Body helpers ──────────────────────────────────────────────────────────
 
/**
 * Recursively build an example JSON value from a ContractTypeNode.
 *
 * When `randomExamples` is true we substitute Bruno faker templates only for
 * scalars whose JSON representation is a string (uuid/email/url/datetime).
 * Numbers and booleans stay deterministic — embedding `{{$randomInt}}` as a
 * bare JSON number would require sentinel-stripping the surrounding quotes,
 * and the body skeleton is meant as a starting point users edit anyway.
 */
function typeToExampleValue(type: ContractTypeNode, modelMap: Map<string, ModelNode>, randomExamples = false): unknown {
    switch (type.kind) {
        case 'scalar':
            switch (type.name) {
                case 'string':
                    return '';
                case 'email':
                    return randomExamples ? '{{$randomEmail}}' : 'user@example.com';
                case 'url':
                    return randomExamples ? '{{$randomUrl}}' : 'https://example.com';
                case 'uuid':
                    return randomExamples ? '{{$randomUUID}}' : '00000000-0000-0000-0000-000000000000';
                case 'number':
                case 'int':
                case 'bigint':
                    return 0;
                case 'boolean':
                    return true;
                case 'date':
                    return '2024-01-01';
                case 'time':
                    return '00:00:00';
                case 'datetime':
                    return randomExamples ? '{{$isoTimestamp}}' : '2024-01-01T00:00:00Z';
                case 'duration':
                    return 'PT1H';
                case 'null':
                    return null;
                default:
                    return null;
            }
        case 'enum':
            return type.values[0] ?? '';
        case 'literal':
            return type.value;
        case 'array':
            return [typeToExampleValue(type.item, modelMap, randomExamples)];
        case 'tuple':
            return type.items.map(t => typeToExampleValue(t, modelMap, randomExamples));
        case 'record':
            return {};
        case 'union':
            return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;
        case 'discriminatedUnion':
            return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;
        case 'intersection':
            return {};
        case 'ref': {
            const model = modelMap.get(type.name);
            if (!model) return {};
            // Type alias — recurse into the aliased type
            Iif (model.type) return typeToExampleValue(model.type, modelMap, randomExamples);
            return modelToExampleObject(model, modelMap, randomExamples);
        }
        case 'lazy':
            return typeToExampleValue(type.inner, modelMap, randomExamples);
        case 'inlineObject':
            return fieldsToExampleObject(type.fields, modelMap, randomExamples);
        default:
            return null;
    }
}
 
/** Build an example object from a ModelNode's fields (including inherited base fields). */
function modelToExampleObject(model: ModelNode, modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {
    return fieldsToExampleObject(resolveModelFields(model, modelMap), modelMap, randomExamples);
}
 
/** Build an example object from a list of FieldNodes. Excludes readonly fields; uses defaults when available; omits optional fields that have no default so they don't appear in the JSON output. */
function fieldsToExampleObject(fields: FieldNode[], modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {
    const obj: Record<string, unknown> = {};
    for (const field of fields) {
        if (field.visibility === 'readonly') continue;
        if (field.default !== undefined) {
            obj[field.name] = field.default;
        } else if (!field.optional) {
            obj[field.name] = typeToExampleValue(field.type, modelMap, randomExamples);
        }
    }
    return obj;
}
 
// ─── Path helpers ──────────────────────────────────────────────────────────
 
/** Convert /users/{id}/posts → /users/:id/posts (Bruno path parameter syntax) */
function openCollectionPath(path: string): string {
    return path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, ':$1');
}
 
/** Convert "Create an Offer" → create-an-offer (for .yml file names) */
export function slugifyName(name: string): string {
    const result = name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');
    return result || 'request';
}
 
/** Convert /users/{id}/posts → users-id-posts (for .yml file names) */
export function sanitizePath(path: string): string {
    const result = path
        .replace(/^\//, '')
        .replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, '$1')
        .replace(/\//g, '-')
        .replace(/[^a-zA-Z0-9-]/g, '')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
    return result || 'root';
}
 
/** Extract param names from a URL template, e.g. /users/{id} → ['id'] */
function extractPathParamNames(path: string): string[] {
    return [...path.matchAll(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g)].map(m => m[1]!);
}
 
/** Derive folder name from op file path, e.g. src/users.op → users */
function deriveFolderName(file: string): string {
    return basename(file).replace(/\.(op|ck)$/, '');
}
 
/**
 * Wrap a string in YAML double quotes if it contains characters that require quoting
 * (flow indicators, colons, braces, etc.).
 */
function yamlString(value: string): string {
    if (/[:{}[\],&*#?|<>=!%@`"']/.test(value) || /^\s|\s$/.test(value)) {
        return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
    }
    return value;
}