All files / src ts-render.ts

82.19% Statements 60/73
85.39% Branches 76/89
72.22% Functions 13/18
87.09% Lines 54/62

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    5x     165x         20x 20x   48x 48x               330x   164x   20x   20x       20x     2x   2x   10x   5x   3x   1x   4x   115x   2x   8x             164x         113x     23x   6x   2x         4x   4x   2x   2x   2x   6x             8x 12x 12x   8x                 89x 43x   15x   4x   4x       4x     6x   2x       3x   1x   16x                     91x 8x   3x   1x   1x       1x                         4x      
import type { ContractTypeNode, FieldNode } from '@contractkit/core';
 
export const JSON_VALUE_TYPE_DECL = 'export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };';
 
export function quoteKey(name: string): string {
    return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? name : `'${name}'`;
}
 
/** Convert an HTTP header name (e.g. `preference-applied`, `X-Request-ID`, `ETag`) to camelCase for use as a JS property. */
export function headerNameToProperty(name: string): string {
    const parts = name.split(/[-_]/).filter(Boolean);
    return parts
        .map((p, i) => {
            const lower = p.toLowerCase();
            return i === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);
        })
        .join('');
}
 
// ─── TypeScript type rendering ────────────────────────────────────────────
 
export 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':
        case 'interval':
            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 `${quoteKey(f.name)}${opt}: ${renderTsType(f.type)}`;
    });
    return `{ ${entries.join('; ')} }`;
}
 
/**
 * Like renderTsType, but substitutes model refs with their Input variant
 * when the model has visibility modifiers. Used for request-side types
 * (body, params, query, headers).
 */
export function renderInputTsType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {
    if (!modelsWithInput || modelsWithInput.size === 0) return renderTsType(type);
    switch (type.kind) {
        case 'ref':
            return modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;
        case 'array': {
            const inner = renderInputTsType(type.item, modelsWithInput);
            const needsParens =
                type.item.kind === 'union' ||
                type.item.kind === 'discriminatedUnion' ||
                type.item.kind === 'intersection' ||
                type.item.kind === 'enum';
            return needsParens ? `(${inner})[]` : `${inner}[]`;
        }
        case 'intersection':
            return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' & ');
        case 'union':
            return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' | ');
        case 'discriminatedUnion':
            return type.members.map(m => renderInputTsType(m, modelsWithInput)).join(' | ');
        case 'inlineObject':
            return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderInputTsType(f.type, modelsWithInput)}`).join('; ')} }`;
        case 'lazy':
            return renderInputTsType(type.inner, modelsWithInput);
        default:
            return renderTsType(type);
    }
}
 
/**
 * Like renderTsType, but substitutes model refs with their Output variant
 * (post-transform wire shape) when the model has format(output=...) or
 * transitively references one. Used for response-side types in routers
 * and SDK return types.
 */
export function renderOutputTsType(type: ContractTypeNode, modelsWithOutput?: Set<string>): string {
    if (!modelsWithOutput || modelsWithOutput.size === 0) return renderTsType(type);
    switch (type.kind) {
        case 'ref':
            return modelsWithOutput.has(type.name) ? `${type.name}Output` : type.name;
        case 'array': {
            const inner = renderOutputTsType(type.item, modelsWithOutput);
            const needsParens =
                type.item.kind === 'union' ||
                type.item.kind === 'discriminatedUnion' ||
                type.item.kind === 'intersection' ||
                type.item.kind === 'enum';
            return needsParens ? `(${inner})[]` : `${inner}[]`;
        }
        case 'intersection':
            return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' & ');
        case 'union':
            return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' | ');
        case 'discriminatedUnion':
            return type.members.map(m => renderOutputTsType(m, modelsWithOutput)).join(' | ');
        case 'inlineObject':
            return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderOutputTsType(f.type, modelsWithOutput)}`).join('; ')} }`;
        case 'lazy':
            return renderOutputTsType(type.inner, modelsWithOutput);
        default:
            return renderTsType(type);
    }
}