All files / src ast-to-ck.ts

90.65% Statements 194/214
82.01% Branches 155/189
100% Functions 18/18
91.91% Lines 182/198

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                                2x                   47x 47x 47x     47x 47x     47x 46x       47x 45x     47x                       47x 47x 47x   47x   11x   11x 10x 10x 10x   10x     11x 2x 2x 2x   2x     11x                         11x 11x           46x     46x 46x 1x   46x 1x   46x 1x     46x 46x     46x 2x 2x       44x 1x   43x     44x 122x     44x 44x       124x 124x 124x 124x   124x     124x 1x     124x 124x   124x       1x 1x 1x       13x   11x     2x           294x   169x   18x   1x   11x   26x   3x   1x   1x   1x   61x   1x   1x                       169x 169x 169x 169x 169x 169x   169x 39x       18x 18x 18x 18x       3x 2x       1x 1x   1x 1x 2x   1x 1x           45x   45x 45x 45x     45x 13x       45x         45x 66x     45x 45x       66x 66x 66x 66x   66x     66x 2x       66x 55x       66x           66x 12x       66x 11x       66x         66x 12x       66x 66x     66x 66x       111x 1x       24x     24x 1x 1x       23x           23x 24x 24x 23x 23x 23x     23x 23x 23x   23x       12x 12x 12x 12x   12x       66x 66x 66x 76x 76x 76x 54x 54x 53x   54x 3x 3x 4x 4x 4x   3x   54x   22x     66x       12x 12x 11x 11x     1x 1x 1x 1x 1x 1x          
import type {
    CkRootNode,
    ModelNode,
    FieldNode,
    ContractTypeNode,
    OpRouteNode,
    OpOperationNode,
    OpRequestNode,
    OpResponseNode,
    ParamSource,
    SecurityNode,
    SecurityFields,
    ObjectMode,
    RouteModifier,
} from '@contractkit/core';
 
const INDENT = '    '; // 4 spaces
 
// ─── Public API ───────────────────────────────────────────────────────────
 
export interface SerializeOptions {
    /** Emit descriptions as inline # comments. Default: true. */
    includeComments?: boolean;
}
 
export function astToCk(root: CkRootNode, options: SerializeOptions = {}): string {
    const { includeComments = true } = options;
    const ctx: Ctx = { includeComments };
    const parts: string[] = [];
 
    // Options block
    const optionsBlock = serializeOptions(root);
    if (optionsBlock) parts.push(optionsBlock);
 
    // Models
    for (const model of root.models) {
        parts.push(serializeModel(model, ctx));
    }
 
    // Routes
    for (const route of root.routes) {
        parts.push(serializeRoute(route, ctx));
    }
 
    return parts.join('\n\n') + '\n';
}
 
// ─── Context ──────────────────────────────────────────────────────────────
 
interface Ctx {
    includeComments: boolean;
}
 
// ─── Options block ────────────────────────────────────────────────────────
 
function serializeOptions(root: CkRootNode): string | null {
    const hasKeys = Object.keys(root.meta).length > 0;
    const hasServices = root.services && Object.keys(root.services).length > 0;
    const hasSecurity = root.security !== undefined;
 
    if (!hasKeys && !hasServices && !hasSecurity) return null;
 
    const lines: string[] = ['options {'];
 
    if (hasKeys) {
        lines.push(`${INDENT}keys: {`);
        for (const [key, value] of Object.entries(root.meta)) {
            lines.push(`${INDENT}${INDENT}${key}: ${value}`);
        }
        lines.push(`${INDENT}}`);
    }
 
    if (hasServices) {
        lines.push(`${INDENT}services: {`);
        for (const [name, path] of Object.entries(root.services)) {
            lines.push(`${INDENT}${INDENT}${name}: "${path}"`);
        }
        lines.push(`${INDENT}}`);
    }
 
    Iif (hasSecurity) {
        lines.push(`${INDENT}security: {`);
        if (root.security === 'none') {
            lines.push(`${INDENT}${INDENT}none`);
        } else {
            const sec = root.security as SecurityFields;
            if (sec.roles && sec.roles.length > 0) {
                lines.push(`${INDENT}${INDENT}roles: [${sec.roles.join(', ')}]`);
            }
        }
        lines.push(`${INDENT}}`);
    }
 
    lines.push('}');
    return lines.join('\n');
}
 
// ─── Models ───────────────────────────────────────────────────────────────
 
function serializeModel(model: ModelNode, ctx: Ctx): string {
    const parts: string[] = [];
 
    // Modifiers: format(input=snake) mode(loose) deprecated
    const prefixes: string[] = [];
    if (model.inputCase && model.inputCase !== 'camel') {
        prefixes.push(`format(input=${model.inputCase})`);
    }
    if (model.mode && model.mode !== 'strict') {
        prefixes.push(`mode(${model.mode})`);
    }
    if (model.deprecated) {
        prefixes.push('deprecated');
    }
 
    const prefix = prefixes.length > 0 ? prefixes.join(' ') + ' ' : '';
    const comment = ctx.includeComments && model.description ? ` # ${model.description}` : '';
 
    // Type alias: contract Name: typeExpression
    if (model.type) {
        parts.push(`contract ${prefix}${model.name}: ${serializeType(model.type)}${comment}`);
        return parts.join('');
    }
 
    // Inheritance: contract Name: Base1 & Base2 & { ... }
    if (model.bases && model.bases.length > 0) {
        parts.push(`contract ${prefix}${model.name}: ${model.bases.join(' & ')} & {${comment}`);
    } else {
        parts.push(`contract ${prefix}${model.name}: {${comment}`);
    }
 
    for (const field of model.fields) {
        parts.push(serializeField(field, 1, ctx));
    }
 
    parts.push('}');
    return parts.join('\n');
}
 
function serializeField(field: FieldNode, depth: number, ctx: Ctx): string {
    const indent = INDENT.repeat(depth);
    const optional = field.optional ? '?' : '';
    const visibility = field.visibility !== 'normal' ? `${field.visibility} ` : '';
    const deprecated = field.deprecated ? 'deprecated ' : '';
 
    let typeStr = serializeType(field.type);
 
    // Nullable fields: if the type doesn't already contain null, append `| null`
    if (field.nullable && !typeContainsNull(field.type)) {
        typeStr = `${typeStr} | null`;
    }
 
    const defaultVal = field.default !== undefined ? ` = ${serializeDefault(field.default)}` : '';
    const comment = ctx.includeComments && field.description ? ` # ${field.description}` : '';
 
    return `${indent}${field.name}${optional}: ${deprecated}${visibility}${typeStr}${defaultVal}${comment}`;
}
 
function typeContainsNull(type: ContractTypeNode): boolean {
    Iif (type.kind === 'scalar' && type.name === 'null') return true;
    Iif (type.kind === 'union') return type.members.some(typeContainsNull);
    return false;
}
 
function serializeDefault(value: string | number | boolean): string {
    if (typeof value === 'string') {
        // If it looks like an identifier (e.g. enum value), don't quote it
        Eif (/^[a-zA-Z_$][a-zA-Z0-9_$\-.]*$/.test(value)) return value;
        return `"${value}"`;
    }
    return String(value);
}
 
// ─── Types ────────────────────────────────────────────────────────────────
 
export function serializeType(type: ContractTypeNode): string {
    switch (type.kind) {
        case 'scalar':
            return serializeScalar(type);
        case 'array':
            return serializeArray(type);
        case 'tuple':
            return `tuple(${type.items.map(serializeType).join(', ')})`;
        case 'record':
            return `record(${serializeType(type.key)}, ${serializeType(type.value)})`;
        case 'enum':
            return `enum(${type.values.join(', ')})`;
        case 'literal':
            return serializeLiteral(type);
        case 'union':
            return type.members.map(serializeType).join(' | ');
        case 'discriminatedUnion':
            return `discriminated(by=${type.discriminator}, ${type.members.map(serializeType).join(' | ')})`;
        case 'intersection':
            return type.members.map(serializeType).join(' & ');
        case 'ref':
            return type.name;
        case 'inlineObject':
            return serializeInlineObject(type);
        case 'lazy':
            return `lazy(${serializeType(type.inner)})`;
    }
}
 
function serializeScalar(type: {
    name: string;
    min?: number | bigint | string;
    max?: number | bigint | string;
    len?: number;
    regex?: string;
    format?: string;
}): string {
    const args: string[] = [];
    if (type.len !== undefined) args.push(`length=${type.len}`);
    if (type.min !== undefined) args.push(typeof type.min === 'string' ? `min="${type.min}"` : `min=${type.min}`);
    if (type.max !== undefined) args.push(typeof type.max === 'string' ? `max="${type.max}"` : `max=${type.max}`);
    if (type.regex !== undefined) args.push(`regex=${type.regex}`);
    Iif (type.format !== undefined) args.push(`format=${type.format}`);
 
    if (args.length === 0) return type.name;
    return `${type.name}(${args.join(', ')})`;
}
 
function serializeArray(type: { item: ContractTypeNode; min?: number; max?: number }): string {
    const args: string[] = [serializeType(type.item)];
    if (type.min !== undefined) args.push(`min=${type.min}`);
    if (type.max !== undefined) args.push(`max=${type.max}`);
    return `array(${args.join(', ')})`;
}
 
function serializeLiteral(type: { value: string | number | boolean }): string {
    if (typeof type.value === 'string') return `literal("${type.value}")`;
    return `literal(${type.value})`;
}
 
function serializeInlineObject(type: { fields: FieldNode[]; mode?: ObjectMode }): string {
    const modePrefix = type.mode ? `mode(${type.mode}) ` : '';
    Iif (type.fields.length === 0) return `${modePrefix}{}`;
 
    const lines: string[] = [`${modePrefix}{`];
    for (const field of type.fields) {
        lines.push(serializeField(field, 2, { includeComments: true }));
    }
    lines.push(`${INDENT}}`);
    return lines.join('\n');
}
 
// ─── Routes ───────────────────────────────────────────────────────────────
 
function serializeRoute(route: OpRouteNode, ctx: Ctx): string {
    const lines: string[] = [];
 
    const modStr = serializeModifiers(route.modifiers);
    const comment = ctx.includeComments && route.description ? ` # ${route.description}` : '';
    lines.push(`operation${modStr} ${route.path}: {${comment}`);
 
    // Route-level params
    if (route.params) {
        serializeParamSource(lines, 'params', route.params, route.paramsMode, 1, ctx);
    }
 
    // Route-level security
    Iif (route.security !== undefined) {
        serializeSecurityBlock(lines, route.security, 1, ctx);
    }
 
    // Operations
    for (const op of route.operations) {
        serializeOperation(lines, op, 1, ctx);
    }
 
    lines.push('}');
    return lines.join('\n');
}
 
function serializeOperation(lines: string[], op: OpOperationNode, depth: number, ctx: Ctx): string[] {
    const indent = INDENT.repeat(depth);
    const modStr = serializeModifiers(op.modifiers);
    const comment = ctx.includeComments && op.description ? ` # ${op.description}` : '';
    lines.push(`${indent}${op.method}${modStr}: {${comment}`);
 
    const inner = INDENT.repeat(depth + 1);
 
    // Service
    if (op.service) {
        lines.push(`${inner}service: ${op.service}`);
    }
 
    // SDK
    if (op.sdk) {
        lines.push(`${inner}sdk: ${op.sdk}`);
    }
 
    // Signature
    Iif (op.signature) {
        const sigComment = ctx.includeComments && op.signatureDescription ? ` # ${op.signatureDescription}` : '';
        lines.push(`${inner}signature: ${op.signature}${sigComment}`);
    }
 
    // Security
    if (op.security !== undefined) {
        serializeSecurityBlock(lines, op.security, depth + 1, ctx);
    }
 
    // Query
    if (op.query) {
        serializeParamSource(lines, 'query', op.query, op.queryMode, depth + 1, ctx);
    }
 
    // Headers
    Iif (op.headers) {
        serializeParamSource(lines, 'headers', op.headers, op.headersMode, depth + 1, ctx);
    }
 
    // Request
    if (op.request) {
        serializeRequest(lines, op.request, depth + 1);
    }
 
    // Responses
    Eif (op.responses.length > 0) {
        serializeResponses(lines, op.responses, depth + 1);
    }
 
    lines.push(`${indent}}`);
    return lines;
}
 
function serializeModifiers(modifiers?: RouteModifier[]): string {
    if (!modifiers || modifiers.length === 0) return '';
    return `(${modifiers.join(', ')})`;
}
 
function serializeParamSource(lines: string[], keyword: string, source: ParamSource, mode: ObjectMode | undefined, depth: number, ctx: Ctx): void {
    const indent = INDENT.repeat(depth);
 
    // String reference: `query: TypeName`
    if (source.kind === 'ref') {
        lines.push(`${indent}${keyword}: ${source.name}`);
        return;
    }
 
    // ContractTypeNode reference
    Iif (source.kind === 'type') {
        lines.push(`${indent}${keyword}: ${serializeType(source.node)}`);
        return;
    }
 
    // Inline param declarations: `params: { name: type }`
    const modeStr = mode ? `mode(${mode}) ` : '';
    lines.push(`${indent}${keyword}: ${modeStr}{`);
    for (const param of source.nodes) {
        const optional = param.optional ? '?' : '';
        let typeStr = serializeType(param.type);
        Iif (param.nullable && !typeContainsNull(param.type)) {
            typeStr = `${typeStr} | null`;
        }
        const defaultVal = param.default !== undefined ? ` = ${serializeDefault(param.default)}` : '';
        const comment = ctx.includeComments && param.description ? ` # ${param.description}` : '';
        lines.push(`${INDENT.repeat(depth + 1)}${param.name}${optional}: ${typeStr}${defaultVal}${comment}`);
    }
    lines.push(`${indent}}`);
}
 
function serializeRequest(lines: string[], request: OpRequestNode, depth: number): void {
    const indent = INDENT.repeat(depth);
    lines.push(`${indent}request: {`);
    for (const body of request.bodies) {
        lines.push(`${INDENT.repeat(depth + 1)}${body.contentType}: ${serializeType(body.bodyType)}`);
    }
    lines.push(`${indent}}`);
}
 
function serializeResponses(lines: string[], responses: OpResponseNode[], depth: number): void {
    const indent = INDENT.repeat(depth);
    lines.push(`${indent}response: {`);
    for (const resp of responses) {
        const hasBody = resp.bodyType && resp.contentType;
        const hasHeaders = resp.headers && resp.headers.length > 0;
        if (hasBody || hasHeaders) {
            lines.push(`${INDENT.repeat(depth + 1)}${resp.statusCode}: {`);
            if (hasBody) {
                lines.push(`${INDENT.repeat(depth + 2)}${resp.contentType}: ${serializeType(resp.bodyType!)}`);
            }
            if (hasHeaders) {
                lines.push(`${INDENT.repeat(depth + 2)}headers: {`);
                for (const h of resp.headers!) {
                    const opt = h.optional ? '?' : '';
                    const trail = h.description ? ` # ${h.description}` : '';
                    lines.push(`${INDENT.repeat(depth + 3)}${h.name}${opt}: ${serializeType(h.type)}${trail}`);
                }
                lines.push(`${INDENT.repeat(depth + 2)}}`);
            }
            lines.push(`${INDENT.repeat(depth + 1)}}`);
        } else {
            lines.push(`${INDENT.repeat(depth + 1)}${resp.statusCode}:`);
        }
    }
    lines.push(`${indent}}`);
}
 
function serializeSecurityBlock(lines: string[], security: SecurityNode, depth: number, ctx: Ctx): void {
    const indent = INDENT.repeat(depth);
    if (security === 'none') {
        lines.push(`${indent}security: none`);
        return;
    }
 
    const sec = security as SecurityFields;
    if (sec.roles && sec.roles.length > 0) {
        const rolesComment = ctx.includeComments && sec.rolesDescription ? ` # ${sec.rolesDescription}` : '';
        lines.push(`${indent}security: {`);
        lines.push(`${INDENT.repeat(depth + 1)}roles: [${sec.roles.join(', ')}]${rolesComment}`);
        lines.push(`${indent}}`);
    } else E{
        lines.push(`${indent}security: {}`);
    }
}