All files / src schema-to-ast.ts

84.69% Statements 155/183
75% Branches 123/164
95.65% Functions 22/23
87.65% Lines 142/162

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                                                2x       2x                                   19x   19x 40x 40x 40x       19x   19x             40x   40x     40x 1x 1x 1x   1x 1x 1x 1x 1x                         39x 37x 37x                   2x 2x                             259x 46x 46x 46x 1x   45x             213x 1x       212x 23x       189x 2x 1x   1x   187x 1x     1x       186x 1x     1x   2x         185x   185x   1x     1x     184x       184x   114x 114x   38x 38x   2x 2x   2x 2x         14x 14x   14x 14x           184x 1x     183x             114x 41x 41x 41x       73x 73x 1x   72x 72x   73x 73x   73x       38x 38x 38x 38x 38x       2x 2x 2x 2x         14x 1x   2x       13x 14x 14x 13x   13x         14x 11x               3x 2x       1x       2x 2x           40x 40x 40x   40x 115x 115x     115x 115x 115x               115x   115x                         40x           185x   184x 183x     1x 1x 2x 1x 1x 1x                           4x 2x 2x       2x 1x 1x       40x 40x 40x                       53x 32x       21x                               21x               40x       43x     40x 3x     40x    
import type { ContractTypeNode, ScalarTypeNode, ModelNode, FieldNode, SourceLocation } from '@contractkit/core';
import type { NormalizedSchema } from './types.js';
import { extractRefName } from './circular-refs.js';
import type { WarningCollector } from './warnings.js';
 
// ─── Conversion Context ───────────────────────────────────────────────────
 
export interface SchemaContext {
    /** Schema names involved in circular references — use lazy() for these. */
    circularRefs: Set<string>;
    /** Warning collector for unsupported features. */
    warnings: WarningCollector;
    /** Current JSON pointer path (for warnings). */
    path: string;
    /** Whether to include descriptions. */
    includeComments: boolean;
    /** All named schemas (for inline extraction). */
    namedSchemas: Record<string, NormalizedSchema>;
    /** Extracted inline models (accumulated during conversion). */
    extractedModels: ModelNode[];
    /** Counter for generating unique names for inline models. */
    inlineCounter: number;
}
 
const LOC: SourceLocation = { file: '', line: 0 };
 
// ─── Format → Scalar Name Mapping ────────────────────────────────────────
 
const FORMAT_TO_SCALAR: Record<string, ScalarTypeNode['name']> = {
    email: 'email',
    uri: 'url',
    url: 'url',
    uuid: 'uuid',
    date: 'date',
    'date-time': 'datetime',
    time: 'time',
    binary: 'binary',
    int64: 'bigint',
};
 
// ─── Public API ───────────────────────────────────────────────────────────
 
/**
 * Convert all named schemas in components/schemas to ModelNodes.
 */
export function schemasToModels(schemas: Record<string, NormalizedSchema>, ctx: SchemaContext): ModelNode[] {
    const models: ModelNode[] = [];
 
    for (const [name, schema] of Object.entries(schemas)) {
        const modelCtx = { ...ctx, path: `#/components/schemas/${name}` };
        const model = schemaToModel(name, schema, modelCtx);
        Eif (model) models.push(model);
    }
 
    // Append any inline models extracted during conversion
    models.push(...ctx.extractedModels);
 
    return models;
}
 
/**
 * Convert a named schema to a ModelNode.
 */
function schemaToModel(name: string, schema: NormalizedSchema, ctx: SchemaContext): ModelNode | null {
    warnUnsupported(schema, ctx);
 
    const description = ctx.includeComments ? schema.description : undefined;
 
    // allOf with exactly 2 members, one being a $ref → inheritance
    if (schema.allOf && schema.allOf.length === 2) {
        const [first, second] = schema.allOf;
        const refMember = first?.$ref ? first : second?.$ref ? second : null;
        const objectMember = first?.$ref ? second : first;
 
        Eif (refMember?.$ref && objectMember?.properties) {
            const baseName = extractRefName(refMember.$ref);
            Eif (baseName) {
                const fields = schemaPropertiesToFields(objectMember, ctx);
                return {
                    kind: 'model',
                    name,
                    bases: [baseName],
                    fields,
                    description,
                    loc: LOC,
                };
            }
        }
    }
 
    // Object with properties → struct
    if (schema.properties || (schema.type === 'object' && !schema.additionalProperties)) {
        const fields = schemaPropertiesToFields(schema, ctx);
        return {
            kind: 'model',
            name,
            fields,
            description,
            loc: LOC,
        };
    }
 
    // Otherwise → type alias
    const typeNode = schemaToTypeNode(schema, ctx);
    return {
        kind: 'model',
        name,
        fields: [],
        type: typeNode,
        description,
        loc: LOC,
    };
}
 
/**
 * Convert an OpenAPI schema to a ContractTypeNode.
 */
export function schemaToTypeNode(schema: NormalizedSchema, ctx: SchemaContext): ContractTypeNode {
    // $ref
    if (schema.$ref) {
        const refName = extractRefName(schema.$ref);
        Eif (refName) {
            if (ctx.circularRefs.has(refName)) {
                return { kind: 'lazy', inner: { kind: 'ref', name: refName } };
            }
            return { kind: 'ref', name: refName };
        }
        ctx.warnings.warn(ctx.path, `Unresolvable $ref: ${schema.$ref}`);
        return { kind: 'scalar', name: 'unknown' };
    }
 
    // const
    if (schema.const !== undefined) {
        return { kind: 'literal', value: schema.const as string | number | boolean };
    }
 
    // enum
    if (schema.enum) {
        return { kind: 'enum', values: schema.enum.map(String) };
    }
 
    // oneOf / anyOf → union (or discriminatedUnion when discriminator.propertyName is set)
    if (schema.oneOf && schema.oneOf.length > 0) {
        if (schema.discriminator?.propertyName) {
            return toDiscriminatedUnion(schema.oneOf, schema.discriminator.propertyName, ctx);
        }
        return toUnion(schema.oneOf, ctx);
    }
    if (schema.anyOf && schema.anyOf.length > 0) {
        Iif (schema.discriminator?.propertyName) {
            return toDiscriminatedUnion(schema.anyOf, schema.discriminator.propertyName, ctx);
        }
        return toUnion(schema.anyOf, ctx);
    }
 
    // allOf → intersection
    if (schema.allOf && schema.allOf.length > 0) {
        Iif (schema.allOf.length === 1) {
            return schemaToTypeNode(schema.allOf[0]!, ctx);
        }
        return {
            kind: 'intersection',
            members: schema.allOf.map(s => schemaToTypeNode(s, ctx)),
        };
    }
 
    // Handle nullable type arrays: [string, null] → nullable
    const types = normalizeTypeField(schema);
 
    if (types === null) {
        // No type information at all
        Iif (schema.properties) {
            return schemaToInlineObject(schema, ctx);
        }
        return { kind: 'scalar', name: 'unknown' };
    }
 
    const { baseType, nullable } = types;
 
    let typeNode: ContractTypeNode;
 
    switch (baseType) {
        case 'string':
            typeNode = stringSchemaToType(schema);
            break;
        case 'integer':
            typeNode = integerSchemaToType(schema);
            break;
        case 'number':
            typeNode = numberSchemaToType(schema);
            break;
        case 'boolean':
            typeNode = { kind: 'scalar', name: 'boolean' };
            break;
        case 'null':
            typeNode = { kind: 'scalar', name: 'null' };
            break;
        case 'array':
            typeNode = arraySchemaToType(schema, ctx);
            break;
        case 'object':
            typeNode = objectSchemaToType(schema, ctx);
            break;
        default:
            ctx.warnings.warn(ctx.path, `Unknown type: ${baseType}`);
            typeNode = { kind: 'scalar', name: 'unknown' };
    }
 
    if (nullable) {
        return { kind: 'union', members: [typeNode, { kind: 'scalar', name: 'null' }] };
    }
 
    return typeNode;
}
 
// ─── Type-Specific Converters ─────────────────────────────────────────────
 
function stringSchemaToType(schema: NormalizedSchema): ContractTypeNode {
    // Check format first
    if (schema.format) {
        const scalarName = FORMAT_TO_SCALAR[schema.format];
        Eif (scalarName) {
            return { kind: 'scalar', name: scalarName };
        }
    }
 
    const mods: Partial<ScalarTypeNode> = {};
    if (schema.minLength !== undefined && schema.maxLength !== undefined && schema.minLength === schema.maxLength) {
        mods.len = schema.minLength;
    } else {
        if (schema.minLength !== undefined) mods.min = schema.minLength;
        if (schema.maxLength !== undefined) mods.max = schema.maxLength;
    }
    if (schema.pattern) mods.regex = `/${schema.pattern}/`;
    Iif (schema.format && !FORMAT_TO_SCALAR[schema.format]) mods.format = schema.format;
 
    return { kind: 'scalar', name: 'string', ...mods };
}
 
function integerSchemaToType(schema: NormalizedSchema): ContractTypeNode {
    const name: ScalarTypeNode['name'] = schema.format === 'int64' ? 'bigint' : 'int';
    const mods: Partial<ScalarTypeNode> = {};
    if (schema.minimum !== undefined) mods.min = schema.minimum;
    if (schema.maximum !== undefined) mods.max = schema.maximum;
    return { kind: 'scalar', name, ...mods };
}
 
function numberSchemaToType(schema: NormalizedSchema): ContractTypeNode {
    const mods: Partial<ScalarTypeNode> = {};
    Iif (schema.minimum !== undefined) mods.min = schema.minimum;
    Iif (schema.maximum !== undefined) mods.max = schema.maximum;
    return { kind: 'scalar', name: 'number', ...mods };
}
 
function arraySchemaToType(schema: NormalizedSchema, ctx: SchemaContext): ContractTypeNode {
    // Tuple: prefixItems (OAS 3.1)
    if (schema.prefixItems && schema.prefixItems.length > 0) {
        return {
            kind: 'tuple',
            items: schema.prefixItems.map(s => schemaToTypeNode(s, ctx)),
        };
    }
 
    const item = schema.items ? schemaToTypeNode(schema.items, ctx) : { kind: 'scalar' as const, name: 'unknown' as const };
    const mods: { min?: number; max?: number } = {};
    if (schema.minItems !== undefined) mods.min = schema.minItems;
    if (schema.maxItems !== undefined) mods.max = schema.maxItems;
 
    return { kind: 'array', item, ...mods };
}
 
function objectSchemaToType(schema: NormalizedSchema, ctx: SchemaContext): ContractTypeNode {
    // Record type: additionalProperties with no named properties
    if (schema.additionalProperties && typeof schema.additionalProperties === 'object' && !schema.properties) {
        return {
            kind: 'record',
            key: { kind: 'scalar', name: 'string' },
            value: schemaToTypeNode(schema.additionalProperties, ctx),
        };
    }
 
    // Object with properties → inline object or extracted model
    if (schema.properties) {
        return schemaToInlineObject(schema, ctx);
    }
 
    // Empty object
    return { kind: 'scalar', name: 'object' };
}
 
function schemaToInlineObject(schema: NormalizedSchema, ctx: SchemaContext): ContractTypeNode {
    const fields = schemaPropertiesToFields(schema, ctx);
    return { kind: 'inlineObject', fields };
}
 
// ─── Field Conversion ─────────────────────────────────────────────────────
 
function schemaPropertiesToFields(schema: NormalizedSchema, ctx: SchemaContext): FieldNode[] {
    const properties = schema.properties ?? {};
    const required = new Set(schema.required ?? []);
    const fields: FieldNode[] = [];
 
    for (const [name, propSchema] of Object.entries(properties)) {
        const propCtx = { ...ctx, path: `${ctx.path}/properties/${name}` };
        const fieldType = schemaToTypeNode(propSchema, propCtx);
 
        // Determine nullable from the type (if it's a union with null)
        let nullable = false;
        let effectiveType = fieldType;
        Iif (fieldType.kind === 'union') {
            const nonNull = fieldType.members.filter(m => !(m.kind === 'scalar' && m.name === 'null'));
            if (nonNull.length < fieldType.members.length) {
                nullable = true;
                effectiveType = nonNull.length === 1 ? nonNull[0]! : { kind: 'union', members: nonNull };
            }
        }
 
        const visibility = propSchema.readOnly ? ('readonly' as const) : propSchema.writeOnly ? ('writeonly' as const) : ('normal' as const);
 
        fields.push({
            name,
            optional: !required.has(name),
            nullable,
            visibility,
            type: effectiveType,
            default: propSchema.default as string | number | boolean | undefined,
            deprecated: propSchema.deprecated,
            description: ctx.includeComments ? propSchema.description : undefined,
            loc: LOC,
        });
    }
 
    return fields;
}
 
// ─── Helpers ──────────────────────────────────────────────────────────────
 
function normalizeTypeField(schema: NormalizedSchema): { baseType: string; nullable: boolean } | null {
    if (!schema.type) return null;
 
    if (typeof schema.type === 'string') {
        return { baseType: schema.type, nullable: false };
    }
 
    Eif (Array.isArray(schema.type)) {
        const types = schema.type as string[];
        const nonNull = types.filter(t => t !== 'null');
        const nullable = types.includes('null');
        Eif (nonNull.length === 1) {
            return { baseType: nonNull[0]!, nullable };
        }
        // Multiple non-null types — unusual but handle gracefully
        if (nonNull.length === 0) {
            return { baseType: 'null', nullable: false };
        }
        // Multiple types → treat as unknown
        return { baseType: nonNull[0]!, nullable };
    }
 
    return null;
}
 
function toUnion(schemas: NormalizedSchema[], ctx: SchemaContext): ContractTypeNode {
    const members = schemas.map(s => schemaToTypeNode(s, ctx));
    Iif (members.length === 1) return members[0]!;
    return { kind: 'union', members };
}
 
function toDiscriminatedUnion(schemas: NormalizedSchema[], discriminator: string, ctx: SchemaContext): ContractTypeNode {
    const members = schemas.map(s => schemaToTypeNode(s, ctx));
    Iif (members.length === 1) return members[0]!;
    return { kind: 'discriminatedUnion', discriminator, members };
}
 
function warnUnsupported(schema: NormalizedSchema, ctx: SchemaContext): void {
    if (schema.xml) ctx.warnings.warn(ctx.path, 'xml metadata is not supported, skipping');
    Iif (schema.externalDocs) ctx.warnings.info(ctx.path, 'externalDocs is not supported, skipping');
    Iif (schema.not) ctx.warnings.warn(ctx.path, 'not keyword is not supported, skipping');
}
 
/**
 * Extract a named model from an inline object schema (used for request/response bodies).
 */
export function extractInlineModel(
    schema: NormalizedSchema,
    suggestedName: string,
    ctx: SchemaContext,
): { typeNode: ContractTypeNode; model?: ModelNode } {
    // If it's a $ref, just use the ref
    if (schema.$ref) {
        return { typeNode: schemaToTypeNode(schema, ctx) };
    }
 
    // If it's an object with properties, extract as a named model
    Iif (schema.properties || (schema.type === 'object' && schema.additionalProperties === undefined)) {
        const fields = schemaPropertiesToFields(schema, ctx);
        const model: ModelNode = {
            kind: 'model',
            name: suggestedName,
            fields,
            description: ctx.includeComments ? schema.description : undefined,
            loc: LOC,
        };
        return {
            typeNode: { kind: 'ref', name: suggestedName },
            model,
        };
    }
 
    // Otherwise return the type node directly
    return { typeNode: schemaToTypeNode(schema, ctx) };
}
 
/**
 * Sanitize an OpenAPI schema name to a valid .ck identifier (PascalCase).
 */
export function sanitizeName(name: string, warnings: WarningCollector): string {
    // Replace dots, hyphens, spaces, and other invalid chars with word boundaries
    const cleaned = name
        .replace(/[^a-zA-Z0-9_$]/g, ' ')
        .split(/\s+/)
        .filter(Boolean)
        .map(part => part.charAt(0).toUpperCase() + part.slice(1))
        .join('');
 
    if (cleaned !== name) {
        warnings.info(`#/components/schemas/${name}`, `Schema name sanitized: "${name}" → "${cleaned}"`);
    }
 
    return cleaned || 'UnnamedSchema';
}