All files renderer.ts

31% Statements 40/129
17.14% Branches 12/70
25% Functions 12/48
27.67% Lines 31/112

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 3601x   1x 1x 1x 1x 1x 1x 1x 1x                 1x                                                                   16x           1x                                                                                                                                                                                                                                                                                                                                                                                                           4x     4x   4x 4x 4x 4x 4x                                                                                                                         1x             8x 8x 8x 4x     8x   1x       4x             1x 4x 1x 1x        
import { Node, ParameterDeclaration, PropertyDeclaration, SourceFile, TypeParameterDeclaration } from "ts-morph";
import { Nodely } from "./types";
import TS from "./TS";
import { bySyntax } from "./SyntaxKindDelegator";
import SK, { SKindMap } from "./SyntaxKindDelegator.types";
import { $h, $kd, $kind, $section } from "./decorators";
import { cyan, red, yellow } from "console-log-colors";
import { getComments, getExample, getFullName, getName, isMethodLike, isPrimitive, isPrivate } from "./node-tools";
import { getModifiers, getSignature } from "./node-signature";
import { STORY_BOOK_BLOCK } from "./constants";
 
/**
 * Standardizes the properties handled by different function like declarations and expressions.
 * @param typeParams 
 * @param args 
 * @param returnNode 
 * @returns 
 */
const renderFNDetails = (typeParams: TypeParameterDeclaration[], args: ParameterDeclaration[], returnNode?: Node) => {
	const tp = build(...typeParams);
	const ag = build(...args);
	const rt = build(returnNode);
	return [
		...tp ? [
			$section(
				'---',
				$h(5, undefined, "Type Arguments:"),
				tp
			) 
		]:[],
		...ag ? [
			$section(
				'---',
				$h(5, undefined, "Arguments:"),
				ag
			)
		]:[],
		...rt ? [
			$section(
				'---',
				$h(5, undefined, "Returns:"),
				rt
			)
		]:[]
	]
}
 
/**
 * Just a convenient way to combine strings as blocks of text within a file.
 * @param blocks 
 * @returns 
 */
const block = (...blocks: string[]) => blocks.filter(b=>b.trim()).join('\n');
 
 
/**
 * Tweaking node handling via syntax kind
 */
const RENDER_MAP: SKindMap<string> = {
	[SK.TypeAliasDeclaration]: node => {
		const tn = node.getTypeNode();
		const args = node.getTypeParameters();
		const tArgs = build(...args);
		const typed = build();
		return block(
			$h(2, node, $kd`type`, node.getName()+`${args.map(getSignature).join(', ').wrap('<', '>')}`, ':', getSignature(tn)),
			getComments(node),
			getExample(node),
			tArgs ? $section(tArgs):'',
			typed ? $section(typed):''
		);
	},
	[SK.TupleType]: node => build(...node.getElements()),
	[SK.NamedTupleMember]: node => {
		const tn = node.getTypeNode();
		const typed = build(tn);
		return block(
			$h(4, node, $kd`tuple item`, node.getName(), ':', getSignature(tn)),
			getComments(node),
			getExample(node),
			typed ? $section(typed):''
		)
	},
	[SK.TypeLiteral]: node => {
		const properties = node.getProperties();
		const methods = node.getMethods();
		return block(
			properties.length ? $h(5, undefined, 'Properties:'):'',
			build(...properties),
			methods.length ? $h(5, undefined, 'Methods:'):'',
			build(...methods)
		)
	},
	[SK.PropertySignature]: node=>{
		const tn = node.getTypeNode();
		const typed = build(tn);
		return block(
			$h(4, node, getModifiers(node), $kd`${isMethodLike(tn) ? 'method1':'property1'}`, node.getName(), node.hasQuestionToken() ? '?':'', ':', getSignature(tn)),
			getComments(node),
			getExample(node),
			typed ? $section(typed):''
		);
	},
	[SK.PropertyDeclaration]: node=>{
		const tn = node.getTypeNode();
		const typed = build(tn);
		return block(
			$h(4, node, $kd`${node.isStatic() ? 'static ':''}${isMethodLike(tn) ? 'method':'property'}`, node.getName(), ':', getSignature(tn)),
			getComments(node),
			getExample(node),
			typed ? $section(typed):''
		);
	},
	[SK.MethodSignature]: node=>{
		return block(
			$h(4, node, $kd`method`, node.getName(), ':', getSignature(node)),
			getComments(node),
			getExample(node),
			...renderFNDetails(
				node.getTypeParameters(),
				node.getParameters(),
				node.getReturnTypeNode()
			)
		)
	},
	//unlike the method signature
	[SK.FunctionType]: node=>{
		return block(
			...renderFNDetails(
				node.getTypeParameters(),
				node.getParameters(),
				node.getReturnTypeNode()
			),
		);
	},
	[SK.MethodDeclaration]: node=>{
		return block(
			$h(4, node, $kd`${node.isStatic() ? 'static ':''}method`, node.getName(), ':', getSignature(node)),
			getComments(node),
			getExample(node),
			...renderFNDetails(
				node.getTypeParameters(),
				node.getParameters(),
				node.getReturnTypeNode()
			)
		)
	},
	[SK.Parameter]: node=>{
		
		return block(
			$h(4, node, $kd`argument`, getSignature(node)),
			getComments(node),
			getExample(node),
			Node.isObjectBindingPattern(node.getNameNode()) ? build(node.getNameNode()):''
		)
	},
	[SK.TypeParameter]: node=>{
		const constraint = build(node.getConstraint());
		Iif(!constraint) return '';
		return block(
			$h(4, node, $kd`param`, getSignature(node)),
			getComments(node),
			getExample(node),
			constraint ? $section(constraint):''
		)
	},
	[SK.TypeReference]: node=>'',
	[SK.UnionType]: node => build(...node.getTypeNodes()),
	[SK.IntersectionType]: node => build(...node.getTypeNodes()),
	[SK.ArrayType]: node => build(node.getElementTypeNode()),
	[SK.ClassDeclaration]:node => {
		const constructors = build(...node.getConstructors());
		const staticBlocks = build(...node.getStaticBlocks());
		const staticProperties = build(...node.getStaticProperties());
		const staticMethods = build(...node.getStaticMethods());
		const instanceProperties = build(...node.getInstanceProperties());
		const instanceMethods = build(...node.getInstanceMethods());
		return block(
			$h(
				2, 
				node, 
				$kd`class`, 
				node.getName(),
				getSignature(node)
			),
			getComments(node),
			getExample(node),
			$section(
				constructors,
				staticBlocks,
				staticProperties,
				staticMethods,
				instanceProperties,
				instanceMethods
			)
		)
	},
	[SK.ClassStaticBlockDeclaration]: node=>{
		const comments = getComments(node).trim();
		return comments ? block(
			$h(4, undefined, $kd`static block:`),
			comments,
			getExample(node)
		):''
	},
	[SK.Constructor]: node=>block(
		$h(4, node, $kd`constructor`, getSignature(node)),
		getComments(node),
		getExample(node)
	),
	[SK.InterfaceDeclaration]: node=>{
		const typeParams = build(...node.getTypeParameters());
		const extensions = build(...node.getExtends());
		
		const properties: Node[] = [];
		const methods: Node[] = [];
		for(const nds of node.getProperties()){
			if(isMethodLike(nds.getTypeNode())) methods.push(nds);
			else properties.push(nds);
		}
		methods.push(...node.getMethods());
		let data = '';
		Iif(properties.length) data += $h(5, undefined, 'Properties:') + `
${build(...properties)}`;
		Iif(methods.length) data += $h(5, undefined, 'Methods:') + `
${build(...methods)}`;
		return block(
			$h(4, node, $kd`interface`, node.getName(), getSignature(node)),
			...(typeParams ? [
				'---',
				$h(5, undefined, 'Type Parameters:'),
				$section(typeParams)
			]:[]),
			...(extensions ? [
				'---',
				$h(5, undefined, 'Extends:'),
				$section(typeParams)
			]:[]),
			$section(data)
		);
	},
	[SK.ExpressionWithTypeArguments]: node=>{
		return build(...node.getTypeArguments())
	},
	[SK.GetAccessor]: node=>{
		return block(
			$h(4, node, $kd`${node.isStatic() ? 'static ':''}get`, getName(node), ':', getSignature(node))
		)
	},
	[SK.SetAccessor]: node=>{
		return block(
			$h(4, node, $kd`${node.isStatic() ? 'static ':''}set`, getName(node), ':', getSignature(node))
		)
	},
	[SK.ConditionalType]: node=>build(node.getExtendsType(), node.getTrueType(), node.getFalseType()),
	[SK.VariableStatement]: node => {
		return build(...node.getDeclarations())
	},
	[SK.VariableDeclaration]: node => {
		const statement = node.getVariableStatement();
		
		Iif(!statement) return '';
		const dk = statement.getDeclarationKind();
		const tn = node.getTypeNode();
		const initializer = node.getInitializer();
		return block(
			$h(4, node, $kd`${dk}`, getName(node), ':', getSignature(node)),
			getComments(statement),
			getExample(statement),
			build(tn ?? initializer)
		)
	},
	[SK.ObjectBindingPattern]: node => {
		return build(...node.getElements());
	},
	[SK.BindingElement]: node => {
		return build(node.getPropertyNameNode())
	},
	[SK.IndexedAccessType]: node => {
		return build(node.getObjectTypeNode(), node.getIndexTypeNode());
	},
	[SK.FunctionDeclaration]: node => {
		return block(
			$h(4, node, $kd`function`, node.getName(), ':', getSignature(node))
		)
	},
	[SK.ExpressionStatement]: node => '', //expressions are blocks of logic. Currently I dont plan on handling these instances. 
	[SK.ClassExpression]:node => {
		const constructors = build(...node.getConstructors());
		const staticBlocks = build(...node.getStaticBlocks());
		const staticProperties = build(...node.getStaticProperties());
		const staticMethods = build(...node.getStaticMethods());
		const instanceProperties = build(...node.getInstanceProperties());
		const instanceMethods = build(...node.getInstanceMethods());
		return block(
			$h(
				2, 
				node, 
				$kd`class`, 
				node.getName(),
				getSignature(node)
			),
			getComments(node),
			getExample(node),
			$section(
				constructors,
				staticBlocks,
				staticProperties,
				staticMethods,
				instanceProperties,
				instanceMethods
			)
		)
	},
	[SK.ArrayLiteralExpression]: node => build(...node.getElements()),
	[SK.ObjectLiteralExpression]: node => block($section(build(...node.getProperties()))),
	[SK.PropertyAssignment]: node => block(
		$h(4, node, $kd`property`, getSignature(node)),
		getComments(node),
		getExample(node),
		build()
	),
	[SK.ArrowFunction]: node => build(node.getReturnTypeNode()),
	[SK.NewExpression]: ()=>``
};
 
const IGNOREKINDS = new Set([
	SK.ExportDeclaration,
	SK.MultiLineCommentTrivia,
	SK.SingleLineCommentTrivia
]);
 
 
export const build = (...nodes: Nodely[]) => nodes.map(node=>{
	Iif(!TS.documentPrivate && isPrivate(node)) return '';
	return bySyntax(node, RENDER_MAP, n=>{
		if(!n || isPrimitive(n)) return '';
		TS.err("No support", red(n.getKindName()), cyan(n.getKind()), n.getText(), getFullName(n));
		return '';
})}).filter(b=>b.trim()).join('\n');
 
export const renderer = (node: Nodely, df: (node: Nodely)=>string=n=>{
	Iif(!n || isPrimitive(n) || IGNOREKINDS.has(n.getKind())) return '';
	TS.err("No support", red(n.getKindName()), yellow(n.getKind()), getFullName(n));
	return '';
}) => bySyntax(node, RENDER_MAP, df);
 
/**
 * A conveniece to render a source file.
 * @param node 
 * @returns 
 */
export const render = (title: string, node: SourceFile) => {
	const data = node.getChildSyntaxList()?.getChildren().map(c=>renderer(c)).filter(n=>!!n.replace(/\s/g, '')).join('\n---\n');
	Iif(!data) return;
	return `${STORY_BOOK_BLOCK}
<Meta title="${title}"/>
 
${data}`
}