react-tsdoc
Version:
CLI to extract information from React Typescript component files with TSDoc for documentation generation purposes
81 lines (80 loc) • 3.22 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDeclarationParams = exports.getInitializer = exports.resolveType = void 0;
var ts_morph_1 = require("ts-morph");
var typesHelper_1 = require("./typesHelper");
/**
* Resolves a type ref (or returns the literal)
*
* @param node - Type literal or ref to resolve
*/
var resolveType = function (node) {
if (!node)
return null;
// Grab type literal, if any
var typeLiteral = node === null || node === void 0 ? void 0 : node.getLastChildByKind(ts_morph_1.SyntaxKind.TypeLiteral);
// Type literal found, but empty, return
if (typeLiteral && typeLiteral.getChildCount() === 0)
return null;
// Must be a ref
if (!typeLiteral) {
try {
var typeRef = node === null || node === void 0 ? void 0 : node.getFirstChildByKindOrThrow(ts_morph_1.SyntaxKind.TypeReference);
var typeRefIdentifier = typeRef.getFirstChildByKindOrThrow(ts_morph_1.SyntaxKind.Identifier);
// First index is the root definition node
return typeRefIdentifier.getDefinitionNodes()[0] || null;
}
catch (_a) {
return null;
}
}
return typeLiteral;
};
exports.resolveType = resolveType;
/**
* Look for complimentary initializer to param
*
* @param properties - The properties node
* @param paramName - The name of the param
*/
var getInitializer = function (properties, paramName) {
return properties === null || properties === void 0 ? void 0 : properties.forEachChild(function (child) {
var _a, _b;
if (child.getKind() === ts_morph_1.SyntaxKind.BindingElement
&& paramName === ((_a = child.getFirstChildByKind(ts_morph_1.SyntaxKind.Identifier)) === null || _a === void 0 ? void 0 : _a.getText())) {
return (_b = child.getInitializer()) === null || _b === void 0 ? void 0 : _b.getText();
}
});
};
exports.getInitializer = getInitializer;
/**
* Get all the TS params for a given node
*
* @param node - The current AST node
*/
var getDeclarationParams = function (node) {
try {
var params_1 = {};
var paramsNode = node.getParameters()[0];
var propertiesNode_1 = paramsNode.getFirstChildByKind(ts_morph_1.SyntaxKind.ObjectBindingPattern);
var typeNode = (0, exports.resolveType)(paramsNode);
if (!typeNode)
return undefined;
typeNode.getChildrenOfKind(ts_morph_1.SyntaxKind.PropertySignature).forEach(function (param) {
var _a;
var paramName = ((_a = param.getFirstChildByKind(ts_morph_1.SyntaxKind.Identifier)) === null || _a === void 0 ? void 0 : _a.getText()) || '';
var initializer = propertiesNode_1 ? (0, exports.getInitializer)(propertiesNode_1, paramName) : undefined;
params_1[paramName] = {
required: !param.getQuestionTokenNode(),
initializer: initializer,
type: (0, typesHelper_1.getTypeSignature)(param)
};
});
return params_1;
}
catch (error) {
console.log(error);
return undefined;
}
};
exports.getDeclarationParams = getDeclarationParams;
;