All files type-builders.ts

85.58% Statements 95/111
65.11% Branches 84/129
100% Functions 20/20
85.71% Lines 78/91

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              4x 4x 4x                       310x 212x   98x         49x   12x   1x   2x   9x   8x   1x   7x   9x 9x               14x 12x     12x 14x 14x   12x       2x 1x       4x 2x 2x 2x       9x 9x 22x 22x             9x       8x 8x 8x 8x 2x 1x           1x 1x 1x       7x 7x 14x 7x       14x 7x 7x     7x 6x   1x       7x       9x 9x   14x             14x           14x 14x 14x 14x 14x 14x   9x               215x 3x 6x 3x 1x 1x 1x   212x 1x   213x             17x 13x 13x   16x                          
/**
 * Shared type-building utilities used by both contract and operation semantic actions.
 * Extracted from visitor-contract.ts and visitor-op.ts to eliminate duplication.
 */
import type { ContractTypeNode, ScalarTypeNode, UnionTypeNode } from './ast.js';
import { SCALAR_NAMES } from './ast.js';
 
export const OBJECT_MODES = new Set<string>(['strict', 'strip', 'loose']);
export const ROUTE_MODIFIERS = new Set<string>(['internal', 'deprecated', 'public']);
export const HTTP_METHODS = new Set<string>(['get', 'post', 'put', 'patch', 'delete']);
 
/** Parsed type argument — either a key=value constraint or a positional value. */
export type TypeArgKeyValue = { key: string; value: string | number | boolean };
export type TypeArgString = { type: 'string'; value: string };
export type TypeArgNumber = { type: 'number'; value: number };
export type TypeArgBoolean = { type: 'boolean'; value: boolean };
export type TypeArgType = { type: 'type'; value: ContractTypeNode };
export type TypeArg = TypeArgKeyValue | TypeArgString | TypeArgNumber | TypeArgBoolean | TypeArgType;
 
/** Resolve a simple type name to a ContractTypeNode (scalar or model ref). */
export function resolveSimpleType(name: string): ContractTypeNode {
    if (SCALAR_NAMES.has(name)) {
        return { kind: 'scalar', name: name as ScalarTypeNode['name'] };
    }
    return { kind: 'ref', name };
}
 
/** Build a compound or constrained type from a type name and parsed arguments. */
export function buildCompoundType(name: string, args: TypeArg[]): ContractTypeNode {
    switch (name) {
        case 'array':
            return buildArrayType(args);
        case 'tuple':
            return buildTupleType(args);
        case 'record':
            return buildRecordType(args);
        case 'enum':
            return buildEnumType(args);
        case 'literal':
            return buildLiteralType(args);
        case 'lazy':
            return buildLazyType(args);
        case 'discriminated':
            return buildDiscriminatedUnionType(args);
        default: {
            Eif (SCALAR_NAMES.has(name)) {
                return buildScalarWithModifiers(name as ScalarTypeNode['name'], args);
            }
            return { kind: 'ref', name };
        }
    }
}
 
function buildArrayType(args: TypeArg[]): ContractTypeNode {
    const typeArgs = args.filter((a): a is TypeArgType => 'type' in a && a.type === 'type');
    const item: ContractTypeNode = typeArgs[0]?.value ?? { kind: 'scalar', name: 'unknown' };
    let min: number | undefined;
    let max: number | undefined;
    for (const a of args) {
        if ('key' in a && a.key === 'min') min = Number(a.value);
        if ('key' in a && a.key === 'max') max = Number(a.value);
    }
    return { kind: 'array', item, min, max };
}
 
function buildTupleType(args: TypeArg[]): ContractTypeNode {
    const items = args.filter((a): a is TypeArgType => 'type' in a && a.type === 'type').map(a => a.value);
    return { kind: 'tuple', items };
}
 
function buildRecordType(args: TypeArg[]): ContractTypeNode {
    const typeArgs = args.filter((a): a is TypeArgType => 'type' in a && a.type === 'type');
    const key: ContractTypeNode = typeArgs[0]?.value ?? { kind: 'scalar', name: 'string' };
    const value: ContractTypeNode = typeArgs[1]?.value ?? { kind: 'scalar', name: 'unknown' };
    return { kind: 'record', key, value };
}
 
function buildEnumType(args: TypeArg[]): ContractTypeNode {
    const values: string[] = [];
    for (const a of args) {
        if ('type' in a && a.type === 'type' && a.value.kind === 'ref') {
            values.push(a.value.name);
        } else Eif ('type' in a && a.type === 'string') {
            values.push(a.value);
        } else if ('type' in a && a.type === 'type' && a.value.kind === 'scalar') {
            values.push(a.value.name);
        }
    }
    return { kind: 'enum', values };
}
 
function buildLiteralType(args: TypeArg[]): ContractTypeNode {
    const arg = args[0];
    Iif (!arg) return { kind: 'literal', value: '' };
    Eif ('type' in arg) {
        if (arg.type === 'string') return { kind: 'literal', value: arg.value };
        if (arg.type === 'number') return { kind: 'literal', value: arg.value };
        Eif (arg.type === 'boolean') return { kind: 'literal', value: arg.value };
    }
    return { kind: 'literal', value: String('value' in arg ? arg.value : '') };
}
 
function buildLazyType(args: TypeArg[]): ContractTypeNode {
    const typeArg = args.find((a): a is TypeArgType => 'type' in a && a.type === 'type');
    const inner: ContractTypeNode = typeArg?.value ?? { kind: 'scalar', name: 'unknown' };
    return { kind: 'lazy', inner };
}
 
function buildDiscriminatedUnionType(args: TypeArg[]): ContractTypeNode {
    let discriminator = '';
    for (const a of args) {
        if ('key' in a && a.key === 'by') {
            discriminator = String(a.value);
        }
    }
 
    const typeArgs = args.filter((a): a is TypeArgType => 'type' in a && a.type === 'type');
    const members: ContractTypeNode[] = [];
    for (const ta of typeArgs) {
        // A single TypeExpression like `A | B | C` arrives as one TypeArgType with a union node.
        // Flatten it so members ends up as the leaf types.
        if (ta.value.kind === 'union') {
            members.push(...ta.value.members);
        } else {
            members.push(ta.value);
        }
    }
 
    return { kind: 'discriminatedUnion', discriminator, members };
}
 
function buildScalarWithModifiers(name: ScalarTypeNode['name'], args: TypeArg[]): ScalarTypeNode {
    const scalar: ScalarTypeNode = { kind: 'scalar', name };
    for (const a of args) {
        // Positional string argument (quoted): used as format for date/time types
        Iif ('type' in a && a.type === 'string' && !('key' in a)) {
            if (name === 'date' || name === 'time' || name === 'datetime') {
                scalar.format = String(a.value);
            }
            continue;
        }
        // Positional ref argument (unquoted identifier): used as format for date/time types
        Iif ('type' in a && a.type === 'type' && a.value?.kind === 'ref' && !('key' in a)) {
            if (name === 'date' || name === 'time' || name === 'datetime') {
                scalar.format = String(a.value.name);
            }
            continue;
        }
        Iif (!('key' in a)) continue;
        if (a.key === 'min') scalar.min = name === 'bigint' ? BigInt(a.value) : name === 'duration' ? String(a.value) : Number(a.value);
        if (a.key === 'max') scalar.max = name === 'bigint' ? BigInt(a.value) : name === 'duration' ? String(a.value) : Number(a.value);
        if (a.key === 'len' || a.key === 'length') scalar.len = Number(a.value);
        if (a.key === 'regex') scalar.regex = String(a.value);
        Iif (a.key === 'format') scalar.format = String(a.value);
    }
    return scalar;
}
 
/**
 * Extract nullability from a type node.
 * If the type is a union containing `null`, remove the null member and return nullable=true.
 */
export function extractNullability(type: ContractTypeNode): { type: ContractTypeNode; nullable: boolean } {
    if (type.kind === 'union') {
        const union = type as UnionTypeNode;
        const nullIdx = union.members.findIndex(m => m.kind === 'scalar' && (m as ScalarTypeNode).name === 'null');
        if (nullIdx !== -1) {
            const filtered = [...union.members];
            filtered.splice(nullIdx, 1);
            return { type: filtered.length === 1 ? filtered[0]! : { kind: 'union', members: filtered }, nullable: true };
        }
    } else if (type.kind === 'scalar' && type.name === 'null') {
        return { type, nullable: true };
    }
    return { type, nullable: false };
}
 
/**
 * Convert a ContractTypeNode to ParamSource for query/headers blocks.
 */
export function typeNodeToParamSource(node: ContractTypeNode): import('./ast.js').ParamSource {
    if (node.kind === 'ref') return { kind: 'ref', name: node.name };
    Eif (node.kind === 'inlineObject') {
        return {
            kind: 'params',
            nodes: node.fields.map(f => ({
                name: f.name,
                optional: f.optional,
                nullable: f.nullable,
                type: f.type,
                default: f.default,
                description: f.description,
                loc: f.loc,
            })),
        };
    }
    return { kind: 'type', node: node };
}