All files / metadata resolveType.ts

42.8% Statements 113/264
32.67% Branches 49/150
50% Functions 25/50
45.57% Lines 108/237
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 5031x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x     1x 6x 6x 4x     2x               2x       2x     2x 2x 2x 2x   2x           2x 2x       2x 2x           2x       2x     2x 2x       6x 6x   4x                                             4x                                           2x 2x 4304x 2x   2x                                               2x 2x 4304x   258x 258x   178x   2x                     2x 2x   2x   2x 2x   2x       2x   2x   2x 2x   2x         2x       2x 2x   2x   2x               2x 2x               2x                                                                                                         4304x       2340x 1964x         2x     2x       2x                                               2x       2x 2x   2x     2x   4304x 1964x     2340x 2340x     2x 2x         2x       2x 2x 2x 3x     3x 3x   3x     3x     3x                                                 3x                                                                                                 2x 2x 2x 3x                                                   2x 2x     2x 2x                               2x       5x             5x         5x 5x   5x    
import * as ts from 'typescript';
import { MetadataGenerator, Type, EnumerateType, ReferenceType, ArrayType, Property } from './metadataGenerator';
import { getDecoratorName } from '../utils/decoratorUtils';
import * as _ from 'lodash';
 
const syntaxKindMap: { [kind: number]: string } = {};
syntaxKindMap[ts.SyntaxKind.NumberKeyword] = 'number';
syntaxKindMap[ts.SyntaxKind.StringKeyword] = 'string';
syntaxKindMap[ts.SyntaxKind.BooleanKeyword] = 'boolean';
syntaxKindMap[ts.SyntaxKind.VoidKeyword] = 'void';
 
const localReferenceTypeCache: { [typeName: string]: ReferenceType } = {};
const inProgressTypes: { [typeName: string]: boolean } = {};
 
type UsableDeclaration = ts.InterfaceDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration;
export function ResolveType(typeNode: ts.TypeNode): Type {
    const primitiveType = getPrimitiveType(typeNode);
    if (primitiveType) {
        return primitiveType;
    }
 
    Iif (typeNode.kind === ts.SyntaxKind.ArrayType) {
        const arrayType = typeNode as ts.ArrayTypeNode;
        return <ArrayType>{
            elementType: ResolveType(arrayType.elementType),
            typeName: 'array'
        };
    }
 
    Iif (typeNode.kind === ts.SyntaxKind.UnionType) {
        return { typeName: 'object' };
    }
 
    Iif (typeNode.kind !== ts.SyntaxKind.TypeReference) {
        throw new Error(`Unknown type: ${ts.SyntaxKind[typeNode.kind]}`);
    }
    let typeReference: any = typeNode;
    Eif (typeReference.typeName.kind === ts.SyntaxKind.Identifier) {
        Iif (typeReference.typeName.text === 'Date') { return getDateType(typeNode); }
        Iif (typeReference.typeName.text === 'Buffer') { return { typeName: 'buffer' }; }
 
        Iif (typeReference.typeName.text === 'Promise') {
            typeReference = typeReference.typeArguments[0];
            return ResolveType(typeReference);
        }
    }
 
    const enumType = getEnumerateType(typeNode);
    Iif (enumType) {
        return enumType;
    }
 
    const literalType = getLiteralType(typeNode);
    Iif (literalType) {
        return literalType;
    }
 
    let referenceType: ReferenceType;
 
    Iif (typeReference.typeArguments && typeReference.typeArguments.length === 1) {
        const typeT: ts.TypeNode[] = typeReference.typeArguments as ts.TypeNode[];
        referenceType = getReferenceType(typeReference.typeName as ts.EntityName, typeT);
    } else {
        referenceType = getReferenceType(typeReference.typeName as ts.EntityName);
    }
 
    MetadataGenerator.current.addReferenceType(referenceType);
    return referenceType;
}
 
function getPrimitiveType(typeNode: ts.TypeNode): Type | undefined {
    const primitiveType = syntaxKindMap[typeNode.kind];
    if (!primitiveType) { return; }
 
    Iif (primitiveType === 'number') {
        const parentNode = typeNode.parent as ts.Node;
        if (!parentNode) {
            return { typeName: 'double' };
        }
 
        const decoratorName = getDecoratorName(parentNode, identifier => {
            return ['IsInt', 'IsLong', 'IsFloat', 'isDouble'].some(m => m === identifier.text);
        });
 
        switch (decoratorName) {
            case 'IsInt':
                return { typeName: 'integer' };
            case 'IsLong':
                return { typeName: 'long' };
            case 'IsFloat':
                return { typeName: 'float' };
            case 'IsDouble':
                return { typeName: 'double' };
            default:
                return { typeName: 'double' };
        }
    }
    return { typeName: primitiveType };
}
 
function getDateType(typeNode: ts.TypeNode): Type {
    const parentNode = typeNode.parent as ts.Node;
    if (!parentNode) {
        return { typeName: 'datetime' };
    }
    const decoratorName = getDecoratorName(parentNode, identifier => {
        return ['IsDate', 'IsDateTime'].some(m => m === identifier.text);
    });
    switch (decoratorName) {
        case 'IsDate':
            return { typeName: 'date' };
        case 'IsDateTime':
            return { typeName: 'datetime' };
        default:
            return { typeName: 'datetime' };
    }
}
 
function getEnumerateType(typeNode: ts.TypeNode): EnumerateType | undefined {
    const enumName = (typeNode as any).typeName.text;
    const enumTypes = MetadataGenerator.current.nodes
        .filter(node => node.kind === ts.SyntaxKind.EnumDeclaration)
        .filter(node => (node as any).name.text === enumName);
 
    Eif (!enumTypes.length) { return; }
    if (enumTypes.length > 1) { throw new Error(`Multiple matching enum found for enum ${enumName}; please make enum names unique.`); }
 
    const enumDeclaration = enumTypes[0] as ts.EnumDeclaration;
 
    function getEnumValue(member: any) {
        const initializer = member.initializer;
        if (initializer) {
            if (initializer.expression) {
                return initializer.expression.text;
            }
            return initializer.text;
        }
        return;
    }
    return <EnumerateType>{
        enumMembers: enumDeclaration.members.map((member: any, index) => {
            return getEnumValue(member) || index;
        }),
        typeName: 'enum',
    };
}
 
function getLiteralType(typeNode: ts.TypeNode): EnumerateType | undefined {
    const literalName = (typeNode as any).typeName.text;
    const literalTypes = MetadataGenerator.current.nodes
        .filter(node => node.kind === ts.SyntaxKind.TypeAliasDeclaration)
        .filter(node => {
            const innerType = (node as any).type;
            return innerType.kind === ts.SyntaxKind.UnionType && (innerType as any).types;
        })
        .filter(node => (node as any).name.text === literalName);
 
    Eif (!literalTypes.length) { return; }
    if (literalTypes.length > 1) { throw new Error(`Multiple matching enum found for enum ${literalName}; please make enum names unique.`); }
 
    const unionTypes = (literalTypes[0] as any).type.types;
    return <EnumerateType>{
        enumMembers: unionTypes.map((unionNode: any) => unionNode.literal.text as string),
        typeName: 'enum',
    };
}
 
function getReferenceType(type: ts.EntityName, genericTypes?: ts.TypeNode[]): ReferenceType {
    const typeName = resolveFqTypeName(type);
    const typeNameWithGenerics = getTypeName(typeName, genericTypes);
 
    try {
 
        const existingType = localReferenceTypeCache[typeNameWithGenerics];
        Iif (existingType) { return existingType; }
 
        Iif (inProgressTypes[typeNameWithGenerics]) {
            return createCircularDependencyResolver(typeNameWithGenerics);
        }
 
        inProgressTypes[typeNameWithGenerics] = true;
 
        const modelTypeDeclaration = getModelTypeDeclaration(type);
 
        const properties = getModelTypeProperties(modelTypeDeclaration, genericTypes);
        const additionalProperties = getModelTypeAdditionalProperties(modelTypeDeclaration);
 
        const referenceType: ReferenceType = {
            description: getModelDescription(modelTypeDeclaration),
            properties: properties,
            typeName: typeNameWithGenerics,
        };
        Iif (additionalProperties && additionalProperties.length) {
            referenceType.additionalProperties = additionalProperties;
        }
 
        const extendedProperties = getInheritedProperties(modelTypeDeclaration);
        referenceType.properties = referenceType.properties.concat(extendedProperties);
 
        localReferenceTypeCache[typeNameWithGenerics] = referenceType;
 
        return referenceType;
    } catch (err) {
        console.error(`There was a problem resolving type of '${getTypeName(typeName, genericTypes)}'.`);
        throw err;
    }
}
 
function resolveFqTypeName(type: ts.EntityName): string {
    Eif (type.kind === ts.SyntaxKind.Identifier) {
        return (type as ts.Identifier).text;
    }
 
    const qualifiedType = type as ts.QualifiedName;
    return resolveFqTypeName(qualifiedType.left) + '.' + (qualifiedType.right as ts.Identifier).text;
}
 
function getTypeName(typeName: string, genericTypes?: ts.TypeNode[]): string {
    Eif (!genericTypes || !genericTypes.length) { return typeName; }
    return typeName + genericTypes.map(t => getAnyTypeName(t)).join('');
}
 
function getAnyTypeName(typeNode: ts.TypeNode): string {
    const primitiveType = syntaxKindMap[typeNode.kind];
    if (primitiveType) {
        return primitiveType;
    }
 
    if (typeNode.kind === ts.SyntaxKind.ArrayType) {
        const arrayType = typeNode as ts.ArrayTypeNode;
        return getAnyTypeName(arrayType.elementType) + '[]';
    }
 
    if (typeNode.kind === ts.SyntaxKind.UnionType) {
        return 'object';
    }
 
    if (typeNode.kind !== ts.SyntaxKind.TypeReference) {
        throw new Error(`Unknown type: ${ts.SyntaxKind[typeNode.kind]}`);
    }
 
    const typeReference = typeNode as ts.TypeReferenceNode;
    try {
        return (typeReference.typeName as ts.Identifier).text;
    } catch (e) {
        // idk what would hit this? probably needs more testing
        console.error(e);
        return typeNode.toString();
    }
 
}
 
function createCircularDependencyResolver(typeName: string) {
    const referenceType = {
        description: '',
        properties: new Array<Property>(),
        typeName: typeName,
    };
 
    MetadataGenerator.current.onFinish(referenceTypes => {
        const realReferenceType = referenceTypes[typeName];
        if (!realReferenceType) { return; }
        referenceType.description = realReferenceType.description;
        referenceType.properties = realReferenceType.properties;
        referenceType.typeName = realReferenceType.typeName;
    });
 
    return referenceType;
}
 
function nodeIsUsable(node: ts.Node) {
    switch (node.kind) {
        case ts.SyntaxKind.InterfaceDeclaration:
        case ts.SyntaxKind.ClassDeclaration:
        case ts.SyntaxKind.TypeAliasDeclaration:
            return true;
        default: return false;
    }
}
 
function resolveLeftmostIdentifier(type: ts.EntityName): ts.Identifier {
    while (type.kind !== ts.SyntaxKind.Identifier) {
        type = (type as ts.QualifiedName).left;
    }
    return type as ts.Identifier;
}
 
function resolveModelTypeScope(leftmost: ts.EntityName, statements: any[]): any[] {
    while (leftmost.parent && leftmost.parent.kind === ts.SyntaxKind.QualifiedName) {
        const leftmostName = leftmost.kind === ts.SyntaxKind.Identifier
            ? (leftmost as ts.Identifier).text
            : (leftmost as ts.QualifiedName).right.text;
        const moduleDeclarations = statements
            .filter(node => {
                if (node.kind !== ts.SyntaxKind.ModuleDeclaration) {
                    return false;
                }
 
                const moduleDeclaration = node as ts.ModuleDeclaration;
                return (moduleDeclaration.name as ts.Identifier).text.toLowerCase() === leftmostName.toLowerCase();
            }) as Array<ts.ModuleDeclaration>;
 
        if (!moduleDeclarations.length) { throw new Error(`No matching module declarations found for ${leftmostName}`); }
        if (moduleDeclarations.length > 1) { throw new Error(`Multiple matching module declarations found for ${leftmostName}; please make module declarations unique`); }
 
        const moduleBlock = moduleDeclarations[0].body as ts.ModuleBlock;
        if (moduleBlock === null || moduleBlock.kind !== ts.SyntaxKind.ModuleBlock) { throw new Error(`Module declaration found for ${leftmostName} has no body`); }
 
        statements = moduleBlock.statements;
        leftmost = leftmost.parent as ts.EntityName;
    }
 
    return statements;
}
 
function getModelTypeDeclaration(type: ts.EntityName) {
    const leftmostIdentifier = resolveLeftmostIdentifier(type);
    const statements: any[] = resolveModelTypeScope(leftmostIdentifier, MetadataGenerator.current.nodes);
 
    const typeName = type.kind === ts.SyntaxKind.Identifier
        ? (type as ts.Identifier).text
        : (type as ts.QualifiedName).right.text;
    const modelTypes = statements
        .filter(node => {
            if (!nodeIsUsable(node)) {
                return false;
            }
 
            const modelTypeDeclaration = node as UsableDeclaration;
            return (modelTypeDeclaration.name as ts.Identifier).text === typeName;
        }) as Array<UsableDeclaration>;
 
    Iif (!modelTypes.length) { throw new Error(`No matching model found for referenced type ${typeName}`); }
    Iif (modelTypes.length > 1) {
        const conflicts = modelTypes.map(modelType => modelType.getSourceFile().fileName).join('"; "');
        throw new Error(`Multiple matching models found for referenced type ${typeName}; please make model names unique. Conflicts found: "${conflicts}"`);
    }
 
    return modelTypes[0];
}
 
function getModelTypeProperties(node: UsableDeclaration, genericTypes?: ts.TypeNode[]) {
    Eif (node.kind === ts.SyntaxKind.InterfaceDeclaration) {
        const interfaceDeclaration = node as ts.InterfaceDeclaration;
        return interfaceDeclaration.members
            .filter(member => member.kind === ts.SyntaxKind.PropertySignature)
            .map((member: any) => {
 
                const propertyDeclaration = member as ts.PropertyDeclaration;
                const identifier = propertyDeclaration.name as ts.Identifier;
 
                Iif (!propertyDeclaration.type) { throw new Error('No valid type found for property declaration.'); }
 
                // Declare a variable that can be overridden if needed
                let aType = propertyDeclaration.type;
 
                // aType.kind will always be a TypeReference when the property of Interface<T> is of type T
                Iif (aType.kind === ts.SyntaxKind.TypeReference && genericTypes && genericTypes.length && node.typeParameters) {
 
                    // The type definitions are conviently located on the object which allow us to map -> to the genericTypes
                    const typeParams = _.map(node.typeParameters, (typeParam: ts.TypeParameterDeclaration) => {
                        return typeParam.name.text;
                    });
 
                    // I am not sure in what cases
                    const typeIdentifier = (aType as ts.TypeReferenceNode).typeName;
                    let typeIdentifierName: string;
 
                    // typeIdentifier can either be a Identifier or a QualifiedName
                    if ((typeIdentifier as ts.Identifier).text) {
                        typeIdentifierName = (typeIdentifier as ts.Identifier).text;
                    } else {
                        typeIdentifierName = (typeIdentifier as ts.QualifiedName).right.text;
                    }
 
                    // I could not produce a situation where this did not find it so its possible this check is irrelevant
                    const indexOfType = _.indexOf<string>(typeParams, typeIdentifierName);
                    if (indexOfType >= 0) {
                        aType = genericTypes[indexOfType] as ts.TypeNode;
                    }
                }
 
                return {
                    description: getNodeDescription(propertyDeclaration),
                    name: identifier.text,
                    required: !propertyDeclaration.questionToken,
                    type: ResolveType(aType)
                };
            });
    }
 
    if (node.kind === ts.SyntaxKind.TypeAliasDeclaration) {
        /**
         * TOOD
         *
         * Flesh this out so that we can properly support Type Alii instead of just assuming
         * string literal enums
        */
        return [];
    }
 
    const classDeclaration = node as ts.ClassDeclaration;
 
    let properties = classDeclaration.members.filter((member: any) => {
        if (member.kind !== ts.SyntaxKind.PropertyDeclaration) { return false; }
 
        const propertySignature = member as ts.PropertySignature;
        return propertySignature && hasPublicModifier(propertySignature);
    }) as Array<ts.PropertyDeclaration | ts.ParameterDeclaration>;
 
    const classConstructor = classDeclaration.members.find((member: any) => member.kind === ts.SyntaxKind.Constructor) as ts.ConstructorDeclaration;
    if (classConstructor && classConstructor.parameters) {
        properties = properties.concat(classConstructor.parameters.filter(parameter => hasPublicModifier(parameter)) as any);
    }
 
    return properties
        .map(declaration => {
            const identifier = declaration.name as ts.Identifier;
 
            if (!declaration.type) { throw new Error('No valid type found for property declaration.'); }
 
            return {
                description: getNodeDescription(declaration),
                name: identifier.text,
                required: !declaration.questionToken,
                type: ResolveType(declaration.type)
            };
        });
}
 
function getModelTypeAdditionalProperties(node: UsableDeclaration) {
    Eif (node.kind === ts.SyntaxKind.InterfaceDeclaration) {
        const interfaceDeclaration = node as ts.InterfaceDeclaration;
        return interfaceDeclaration.members
            .filter(member => member.kind === ts.SyntaxKind.IndexSignature)
            .map((member: any) => {
                const indexSignatureDeclaration = member as ts.IndexSignatureDeclaration;
 
                const indexType = ResolveType(<ts.TypeNode>indexSignatureDeclaration.parameters[0].type);
                if (indexType.typeName !== 'string') { throw new Error('Only string indexers are supported'); }
 
                return {
                    description: '',
                    name: '',
                    required: true,
                    type: ResolveType(<ts.TypeNode>indexSignatureDeclaration.type)
                };
            });
    }
 
    return undefined;
}
 
function hasPublicModifier(node: ts.Node) {
    return !node.modifiers || node.modifiers.every(modifier => {
        return modifier.kind !== ts.SyntaxKind.ProtectedKeyword && modifier.kind !== ts.SyntaxKind.PrivateKeyword;
    });
}
 
function getInheritedProperties(modelTypeDeclaration: UsableDeclaration): Property[] {
    const properties = new Array<Property>();
    Iif (modelTypeDeclaration.kind === ts.SyntaxKind.TypeAliasDeclaration) {
        return [];
    }
    const heritageClauses = modelTypeDeclaration.heritageClauses;
    Eif (!heritageClauses) { return properties; }
 
    heritageClauses.forEach(clause => {
        if (!clause.types) { return; }
 
        clause.types.forEach(t => {
            const baseEntityName = t.expression as ts.EntityName;
            getReferenceType(baseEntityName).properties
                .forEach(property => properties.push(property));
        });
    });
 
    return properties;
}
 
function getModelDescription(modelTypeDeclaration: UsableDeclaration) {
    return getNodeDescription(modelTypeDeclaration);
}
 
function getNodeDescription(node: UsableDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration) {
    const symbol = MetadataGenerator.current.typeChecker.getSymbolAtLocation(node.name as ts.Node);
 
    /**
    * TODO: Workaround for what seems like a bug in the compiler
    * Warrants more investigation and possibly a PR against typescript
    */
    //
    Iif (node.kind === ts.SyntaxKind.Parameter) {
        // TypeScript won't parse jsdoc if the flag is 4, i.e. 'Property'
        symbol.flags = 0;
    }
 
    const comments = symbol.getDocumentationComment();
    Iif (comments.length) { return ts.displayPartsToString(comments); }
 
    return '';
}