All files / dist node-signature.js

51.63% Statements 79/153
26.85% Branches 29/108
33.78% Functions 25/74
52.51% Lines 73/139

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                                                              2x 4x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x           2x   12x 12x     2x 14x 2x 1x 1x     2x 1x 1x     2x 2x         2x                     1x 5x 1x 2x 1x   2x         2x                                                           10x   2x 2x   2x 1x   1x     3x 3x 1x 2x 2x 2x       1x 1x 1x               1x 1x 1x               1x 1x                                   2x     2x 2x             2x     2x 9x   9x 9x       44x         2x 12x   2x 2x 2x 2x 2x 2x             2x 2x           2x  
"use strict";
/*
Signature Naming
 
While plain text is a readable method if fails to provide the appropriate information for each name at first glance. instead it seems providing a full signature to each component within the name is the most appropriate method... what does this mean however
 
take the following object for example
 
const Test: {
    getName({name, maternal, paternal}: {
        name: string
        maternal: SomeOtherObject,
        paternal: SomeOtherObject,
    }):{
        name: string,
        lineage(options:{
            branches: 'paternal' | 'maternal' | 'both'
        });
    }
} = {...}
 
This just an example of how anonymous objects can be abused to create something difficult to document.
 
If I were to use simple dot notation to symbolize these nodes I would encounter conflicts with name as it exists with the same syntax multiple times
 
Test.getName.name (the function argument property)
Test.getName.name (the function return value property)
 
It should be noted that vsCode resolves this be resolving destructuring to an any argument called prop.
I think having a method that better at differenciating such things.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSignatureFromType = exports.fromType = exports.isPrimitiveLiteralType = exports.isPrimitiveType = exports.getSignature = exports.getModifiers = void 0;
const node_tools_1 = require("./node-tools");
const SyntaxKindDelegator_1 = require("./SyntaxKindDelegator");
const SyntaxKindDelegator_types_1 = __importDefault(require("./SyntaxKindDelegator.types"));
const decorators_1 = require("./decorators");
const console_log_colors_1 = require("console-log-colors");
const TS_1 = __importDefault(require("./TS"));
const constants_1 = require("./constants");
const utils_1 = require("./utils");
/**
 * With typenodes not alway being provided this method acts as a point where I can change the logic if getting a typenode fails.
 * @param node
 * @returns
 */
const fromTypeNode = (node) => {
    var _a;
    const tn = (0, node_tools_1.getTypeNode)(node);
    return tn ? sig(tn)
        : (_a = (0, exports.getSignatureFromType)(node)) !== null && _a !== void 0 ? _a : '';
};
const objLiteral = () => (0, decorators_1.$literal)(constants_1.typelit);
const genTypes = (nodes, pre = '<', post = '>') => nodes.map(sig).join(', ').wrap(pre, post);
const isAsync = (node) => {
    Eif (!('isAsync' in node) || typeof node.isAsync !== 'function')
        return false;
    return node.isAsync();
};
const isGenerator = (node) => {
    Eif (!('isGenerator' in node) || typeof node.isGenerator !== 'function')
        return false;
    return node.isGenerator();
};
const fnSignature = (node) => `${isAsync(node) ? 'async ' : ''}${isGenerator(node) ? '*' : ''}${genTypes(node.getTypeParameters())}(${genTypes(node.getParameters(), '', '')}) =&gt; ${sig(node.getReturnTypeNode()) || (0, exports.fromType)(node.getReturnType()) || (0, decorators_1.$literal)('void')}`;
const classSignatue = (node) => {
    const extensions = sig(node.getExtends());
    const implementions = node.getImplements().map(i => sig(i)).join(', ');
    return `${extensions ? ' extends ' + extensions : ''}${implementions ? ' implements ' + implementions : ''}`;
};
const typingMap = {
    //functional declarations
    [SyntaxKindDelegator_types_1.default.FunctionDeclaration]: fnSignature,
    [SyntaxKindDelegator_types_1.default.FunctionExpression]: fnSignature,
    [SyntaxKindDelegator_types_1.default.MethodDeclaration]: fnSignature,
    [SyntaxKindDelegator_types_1.default.FunctionType]: fnSignature,
    [SyntaxKindDelegator_types_1.default.MethodSignature]: fnSignature,
    [SyntaxKindDelegator_types_1.default.ArrowFunction]: fnSignature,
    [SyntaxKindDelegator_types_1.default.PropertySignature]: fromTypeNode,
    [SyntaxKindDelegator_types_1.default.BindingElement]: fromTypeNode,
    [SyntaxKindDelegator_types_1.default.PropertyAccessExpression]: node => `${sig(node.getNameNode())}`,
    [SyntaxKindDelegator_types_1.default.UnionType]: node => node.getTypeNodes().map(sig).join(' | '),
    [SyntaxKindDelegator_types_1.default.LiteralType]: node => (0, decorators_1.$literal)(node.getText()),
    [SyntaxKindDelegator_types_1.default.IntersectionType]: node => node.getTypeNodes().map(sig).join(' & '),
    [SyntaxKindDelegator_types_1.default.NamedTupleMember]: node => `${(0, decorators_1.$name)(node.getName())}: ${fromTypeNode(node)}`,
    [SyntaxKindDelegator_types_1.default.ArrayType]: node => `${sig(node.getElementTypeNode())}[]`,
    [SyntaxKindDelegator_types_1.default.ArrayLiteralExpression]: () => '[]',
    [SyntaxKindDelegator_types_1.default.TupleType]: node => genTypes(node.getElements(), '[', ']'),
    [SyntaxKindDelegator_types_1.default.ParenthesizedType]: node => `(${fromTypeNode(node)})`,
    [SyntaxKindDelegator_types_1.default.Constructor]: node => `${(0, decorators_1.$type)("new")} (${node.getParameters().map(p => sig(p)).join(', ')})=>${(0, decorators_1.$type)((0, node_tools_1.getName)(node.getParent()))}`,
    [SyntaxKindDelegator_types_1.default.SetAccessor]: node => node.getParameters().map(p => sig(p)).join(', '),
    [SyntaxKindDelegator_types_1.default.ConditionalType]: node => `${sig(node.getCheckType())} extends ${sig(node.getExtendsType())} ? ${sig(node.getTrueType())}<br/>: ${sig(node.getFalseType())}`,
    [SyntaxKindDelegator_types_1.default.ExpressionWithTypeArguments]: node => `${sig(node.getExpression())}${node.getTypeArguments().map(a => sig(a)).join(', ').wrap('<', '>')}`,
    [SyntaxKindDelegator_types_1.default.RestType]: node => `...${fromTypeNode(node)}`,
    [SyntaxKindDelegator_types_1.default.ArrayBindingPattern]: node => genTypes(node.getElements(), '[', ']'),
    [SyntaxKindDelegator_types_1.default.QualifiedName]: node => `${sig(node.getLeft())}.${sig(node.getRight())}`,
    [SyntaxKindDelegator_types_1.default.TypePredicate]: node => `${sig(node.getParameterNameNode())} ${node.hasAssertsModifier() ? sig(node.getAssertsModifier()) : 'is'} ${sig(node.getTypeNode())}`,
    [SyntaxKindDelegator_types_1.default.TypeOperator]: node => `${(0, decorators_1.$kind)(getOperator(node))} ${fromTypeNode}`,
    [SyntaxKindDelegator_types_1.default.BinaryExpression]: node => `${sig(node.getLeft())} ${sig(node.getOperatorToken())} ${sig(node.getRight())}`,
    [SyntaxKindDelegator_types_1.default.CallExpression]: node => (0, decorators_1.$type)((0, utils_1.escape)(node.getReturnType().getText())),
    [SyntaxKindDelegator_types_1.default.IndexedAccessType]: node => `${sig(node.getObjectTypeNode())}[${node.getIndexTypeNode()}]`,
    //object literat expressions or declarations or types
    [SyntaxKindDelegator_types_1.default.ObjectLiteralExpression]: objLiteral,
    [SyntaxKindDelegator_types_1.default.ObjectBindingPattern]: objLiteral,
    [SyntaxKindDelegator_types_1.default.TypeLiteral]: objLiteral,
    //tokens
    [SyntaxKindDelegator_types_1.default.AsteriskToken]: () => '*',
    [SyntaxKindDelegator_types_1.default.AsteriskAsteriskToken]: () => '**',
    [SyntaxKindDelegator_types_1.default.AsteriskEqualsToken]: () => '*=',
    [SyntaxKindDelegator_types_1.default.AsteriskAsteriskEqualsToken]: () => '**=',
    [SyntaxKindDelegator_types_1.default.PlusToken]: () => '+',
    [SyntaxKindDelegator_types_1.default.PlusPlusToken]: () => '++',
    [SyntaxKindDelegator_types_1.default.PlusEqualsToken]: () => '+=',
    [SyntaxKindDelegator_types_1.default.MinusToken]: () => '-',
    [SyntaxKindDelegator_types_1.default.MinusMinusToken]: () => '--',
    [SyntaxKindDelegator_types_1.default.MinusEqualsToken]: () => '-=',
    [SyntaxKindDelegator_types_1.default.SlashToken]: () => '/',
    [SyntaxKindDelegator_types_1.default.SlashEqualsToken]: () => '/=',
    [SyntaxKindDelegator_types_1.default.LessThanToken]: () => '&lt;',
    [SyntaxKindDelegator_types_1.default.LessThanEqualsToken]: () => '&lt;=',
    [SyntaxKindDelegator_types_1.default.GreaterThanToken]: () => '&gt;',
    [SyntaxKindDelegator_types_1.default.GreaterThanEqualsToken]: () => '&gt;=',
    [SyntaxKindDelegator_types_1.default.TypeAliasDeclaration]: (node) => `${genTypes(node.getTypeParameters())}: ${fromTypeNode(node)}`,
    [SyntaxKindDelegator_types_1.default.TypeReference]: node => {
        const typeName = node.getTypeName();
        const args = node.getTypeArguments();
        //corner cases
        if (typeName.getText() === "Array") {
            return sig(args[0]) + "[]";
        }
        return sig(typeName) + args.map(sig).join(', ').wrap('<', '>');
    },
    [SyntaxKindDelegator_types_1.default.Identifier]: node => {
        const def = node.getDefinitionNodes()[0]; //I guess its possible to have multiple definitions but I havent thought of a use case where I would have reference to all definitions in one location (extensions would have a link back to immediate source automatically)
        if (!def)
            return (0, decorators_1.$type)(node.getText()); //no link
        const href = (0, node_tools_1.getDocPath)(def);
        Eif (!href)
            return (0, decorators_1.$type)(node.getText()); //link outside scope
        return (0, decorators_1.$href)(node.getText(), href);
    },
    [SyntaxKindDelegator_types_1.default.TypeParameter]: node => {
        const extension = node.getConstraint();
        const modifiers = node.getModifiers();
        return `${modifiers.map(sig).join(' ')}${modifiers.length ? ' ' : ''}${(0, decorators_1.$name)(node.getName())}${(extension ? ' extends ' + sig(extension) : '')}`;
    },
    [SyntaxKindDelegator_types_1.default.Parameter]: node => {
        const typeNode = fromTypeNode(node);
        const initializer = sig(node.getInitializer());
        return `${(0, decorators_1.$name)((node.isRestParameter() ? '...' : '') + sig(node.getNameNode()))}: ${typeNode}${initializer ? ' = ' + initializer : ''}`;
    },
    [SyntaxKindDelegator_types_1.default.ClassDeclaration]: node => {
        const extensions = sig(node.getExtends());
        const implementions = node.getImplements().map(i => sig(i)).join(', ');
        return `${extensions ? ' extends ' + extensions : ''}${implementions ? ' implements ' + implementions : ''}`;
    },
    [SyntaxKindDelegator_types_1.default.ClassExpression]: node => {
        const extensions = node.getExtends();
        const implementations = node.getImplements();
        return `${(0, decorators_1.$kd) `class`}${extensions ? (' extends ' + sig(extensions)) : ''}${implementations.map(n => ` implements ${sig(n)}`)}${constants_1.typelit}`;
    },
    [SyntaxKindDelegator_types_1.default.InterfaceDeclaration]: node => {
        const extensions = node.getExtends();
        return `${extensions.map(node => `extends ${sig(node)}`).join(' ')}`;
    },
    [SyntaxKindDelegator_types_1.default.GetAccessor]: node => {
        var _a;
        const rtn = node.getReturnTypeNode();
        return rtn ? sig(rtn)
            : (_a = (0, exports.getSignatureFromType)(node)) !== null && _a !== void 0 ? _a : '';
    },
    [SyntaxKindDelegator_types_1.default.VariableDeclaration]: node => {
        const tn = fromTypeNode(node);
        if (tn)
            return tn;
        const init = node.getInitializer();
        return sig(init);
    },
    [SyntaxKindDelegator_types_1.default.PropertyAssignment]: node => `${sig(node.getNameNode())}: ${fromTypeNode(node)}`,
    [SyntaxKindDelegator_types_1.default.NewExpression]: node => `${sig(node.getExpression())}${genTypes(node.getTypeArguments())}`
};
const getModifiers = (node) => {
    return node.getModifiers().map(m => m.getText()).join(' ');
};
exports.getModifiers = getModifiers;
const getOperator = (node) => {
    switch (node.getOperator()) {
        case SyntaxKindDelegator_types_1.default.ReadonlyKeyword: return 'readonly';
        case SyntaxKindDelegator_types_1.default.KeyOfKeyword: return 'keyof';
        case SyntaxKindDelegator_types_1.default.UniqueKeyword: return 'unique';
    }
};
const Ignores = new Set([
    SyntaxKindDelegator_types_1.default.MultiLineCommentTrivia
]);
const defSig = (n) => {
    Iif (!n || Ignores.has(n.getKind()))
        return '';
    Eif ((0, node_tools_1.isPrimitive)(n))
        return (0, decorators_1.$type)(n.getText());
    TS_1.default.err("Signature Missing type", (0, console_log_colors_1.yellow)(n.getKindName()), (0, console_log_colors_1.gray)((0, node_tools_1.getFullName)(n)), n.getText());
    return "";
};
const sig = (node) => (0, SyntaxKindDelegator_1.bySyntax)(node, typingMap, defSig);
/**
 * Once a full signature name is resolved the typing of the object will be necessary. This typing however will be different for different declaration type. As such I will be handling these similar to the SyntaxKind... I need a SyntaxKind switching function
 * @param node
 */
const getSignature = (node) => {
    return sig(node);
};
exports.getSignature = getSignature;
const isPrimitiveType = (t) => t.isAny() || t.isBigInt() || t.isNumber() || t.isBoolean() || t.isString() || t.isNever() || t.isUndefined() || t.isUnknown() || t.isNull();
exports.isPrimitiveType = isPrimitiveType;
const isPrimitiveLiteralType = (t) => t.isStringLiteral() || t.isNumberLiteral() || t.isBoolean() || t.isBigIntLiteral();
exports.isPrimitiveLiteralType = isPrimitiveLiteralType;
const fromType = (t) => {
    var _a, _b;
    //a node does exist it is just in a body but the return type or type should have a symbol to said declaration... why write a second parser when syntaxKind parser is more convenient. 
    const symbol = (_a = t === null || t === void 0 ? void 0 : t.getSymbol()) === null || _a === void 0 ? void 0 : _a.getDeclarations()[0];
    const aliasSymbol = (_b = t === null || t === void 0 ? void 0 : t.getAliasSymbol()) === null || _b === void 0 ? void 0 : _b.getDeclarations()[0];
    return sig(symbol !== null && symbol !== void 0 ? symbol : aliasSymbol);
};
exports.fromType = fromType;
const getSignatureFromType = (node) => {
    if (!node)
        return '';
    const t = node.getType();
    return (0, exports.fromType)(t);
};
exports.getSignatureFromType = getSignatureFromType;