typescript-docs-parser.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import fs from 'fs';
  2. import path from 'path';
  3. import ts from 'typescript';
  4. import { notNullOrUndefined } from '../../packages/common/src/shared-utils';
  5. import {
  6. ClassInfo,
  7. InterfaceInfo,
  8. MemberInfo,
  9. MethodInfo,
  10. MethodParameterInfo,
  11. ParsedDeclaration,
  12. PropertyInfo,
  13. TypeAliasInfo,
  14. ValidDeclaration,
  15. } from './typescript-docgen-types';
  16. /**
  17. * Parses TypeScript source files into data structures which can then be rendered into
  18. * markdown for documentation.
  19. */
  20. export class TypescriptDocsParser {
  21. private readonly atTokenPlaceholder = '__EscapedAtToken__';
  22. /**
  23. * Parses the TypeScript files given by the filePaths array and returns the
  24. * parsed data structures ready for rendering.
  25. */
  26. parse(filePaths: string[]): ParsedDeclaration[] {
  27. const sourceFiles = filePaths.map(filePath => {
  28. return ts.createSourceFile(
  29. filePath,
  30. this.replaceEscapedAtTokens(fs.readFileSync(filePath).toString()),
  31. ts.ScriptTarget.ES2015,
  32. true,
  33. );
  34. });
  35. const statements = this.getStatementsWithSourceLocation(sourceFiles);
  36. return statements
  37. .map(statement => {
  38. const info = this.parseDeclaration(statement.statement, statement.sourceFile, statement.sourceLine);
  39. return info;
  40. })
  41. .filter(notNullOrUndefined);
  42. }
  43. /**
  44. * Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
  45. * came from.
  46. */
  47. private getStatementsWithSourceLocation(
  48. sourceFiles: ts.SourceFile[],
  49. ): Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }> {
  50. return sourceFiles.reduce(
  51. (st, sf) => {
  52. const statementsWithSources = sf.statements.map(statement => {
  53. const sourceFile = path.relative(path.join(__dirname, '..'), sf.fileName).replace(/\\/g, '/');
  54. const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
  55. return {statement, sourceFile, sourceLine};
  56. });
  57. return [...st, ...statementsWithSources];
  58. },
  59. [] as Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }>,
  60. );
  61. }
  62. /**
  63. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  64. */
  65. private parseDeclaration(
  66. statement: ts.Statement,
  67. sourceFile: string,
  68. sourceLine: number,
  69. ): ParsedDeclaration | undefined {
  70. if (!this.isValidDeclaration(statement)) {
  71. return;
  72. }
  73. const category = this.getDocsCategory(statement);
  74. if (category === undefined) {
  75. return;
  76. }
  77. const title = statement.name ? statement.name.getText() : 'anonymous';
  78. const fullText = this.getDeclarationFullText(statement);
  79. const weight = this.getDeclarationWeight(statement);
  80. const description = this.getDeclarationDescription(statement);
  81. const normalizedTitle = this.kebabCase(title);
  82. const fileName = normalizedTitle === category ? '_index' : normalizedTitle;
  83. const packageName = this.getPackageName(sourceFile);
  84. const info = {
  85. packageName,
  86. sourceFile,
  87. sourceLine,
  88. fullText,
  89. title,
  90. weight,
  91. category,
  92. description,
  93. fileName,
  94. };
  95. if (ts.isInterfaceDeclaration(statement)) {
  96. return {
  97. ...info,
  98. kind: 'interface',
  99. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  100. members: this.parseMembers(statement.members),
  101. };
  102. } else if (ts.isTypeAliasDeclaration(statement)) {
  103. return {
  104. ...info,
  105. type: statement.type,
  106. kind: 'typeAlias',
  107. members: ts.isTypeLiteralNode(statement.type) ? this.parseMembers(statement.type.members) : undefined,
  108. };
  109. } else if (ts.isClassDeclaration(statement)) {
  110. return {
  111. ...info,
  112. kind: 'class',
  113. members: this.parseMembers(statement.members),
  114. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  115. implements: this.getHeritageClauseText(statement, ts.SyntaxKind.ImplementsKeyword),
  116. };
  117. } else if (ts.isEnumDeclaration(statement)) {
  118. return {
  119. ...info,
  120. kind: 'enum' as 'enum',
  121. members: this.parseMembers(statement.members) as PropertyInfo[],
  122. };
  123. } else if (ts.isFunctionDeclaration(statement)) {
  124. const parameters = statement.parameters.map(p => ({
  125. name: p.name.getText(),
  126. type: p.type ? p.type.getText() : '',
  127. optional: !!p.questionToken,
  128. initializer: p.initializer && p.initializer.getText(),
  129. }));
  130. return {
  131. ...info,
  132. kind: 'function',
  133. parameters,
  134. type: statement.type,
  135. };
  136. }
  137. }
  138. /**
  139. * Returns the text of any "extends" or "implements" clause of a class or interface.
  140. */
  141. private getHeritageClauseText(
  142. statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
  143. kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
  144. ): string | undefined {
  145. const {heritageClauses} = statement;
  146. if (!heritageClauses) {
  147. return;
  148. }
  149. const clause = heritageClauses.find(cl => cl.token === kind);
  150. if (!clause) {
  151. return;
  152. }
  153. return clause.getText();
  154. }
  155. /**
  156. * Returns the declaration name plus any type parameters.
  157. */
  158. private getDeclarationFullText(declaration: ValidDeclaration): string {
  159. const name = declaration.name ? declaration.name.getText() : 'anonymous';
  160. let typeParams = '';
  161. if (!ts.isEnumDeclaration(declaration) && declaration.typeParameters) {
  162. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  163. }
  164. return name + typeParams;
  165. }
  166. private getPackageName(sourceFile: string): string {
  167. const matches = sourceFile.match(/\/packages\/([^/]+)\//);
  168. if (matches) {
  169. return `@vendure/${matches[1]}`;
  170. } else {
  171. return '';
  172. }
  173. }
  174. /**
  175. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  176. */
  177. private parseMembers(
  178. members: ts.NodeArray<ts.TypeElement | ts.ClassElement | ts.EnumMember>,
  179. ): Array<PropertyInfo | MethodInfo> {
  180. const result: Array<PropertyInfo | MethodInfo> = [];
  181. for (const member of members) {
  182. const modifiers = member.modifiers ? member.modifiers.map(m => m.getText()) : [];
  183. const isPrivate = modifiers.includes('private');
  184. if (
  185. !isPrivate &&
  186. (ts.isPropertySignature(member) ||
  187. ts.isMethodSignature(member) ||
  188. ts.isPropertyDeclaration(member) ||
  189. ts.isMethodDeclaration(member) ||
  190. ts.isConstructorDeclaration(member) ||
  191. ts.isEnumMember(member) ||
  192. ts.isGetAccessorDeclaration(member)
  193. )
  194. ) {
  195. const name = member.name ? member.name.getText() : 'constructor';
  196. let description = '';
  197. let type = '';
  198. let defaultValue = '';
  199. let parameters: MethodParameterInfo[] = [];
  200. let fullText = '';
  201. let isInternal = false;
  202. if (ts.isConstructorDeclaration(member)) {
  203. fullText = 'constructor';
  204. } else if (ts.isMethodDeclaration(member)) {
  205. fullText = member.name.getText();
  206. } else if (ts.isGetAccessorDeclaration(member)) {
  207. fullText = `${member.name.getText()}: ${member.type ? member.type.getText() : 'void'}`;
  208. } else {
  209. fullText = member.getText();
  210. }
  211. this.parseTags(member, {
  212. description: tag => (description += tag.comment || ''),
  213. example: tag => (description += this.formatExampleCode(tag.comment)),
  214. default: tag => (defaultValue = tag.comment || ''),
  215. internal: tag => isInternal = true,
  216. });
  217. if (isInternal) {
  218. continue;
  219. }
  220. if (!ts.isEnumMember(member) && member.type) {
  221. type = member.type.getText();
  222. }
  223. const memberInfo: MemberInfo = {
  224. fullText,
  225. name,
  226. description: this.restoreAtTokens(description),
  227. type,
  228. modifiers,
  229. };
  230. if (
  231. ts.isMethodSignature(member) ||
  232. ts.isMethodDeclaration(member) ||
  233. ts.isConstructorDeclaration(member)
  234. ) {
  235. parameters = member.parameters.map(p => ({
  236. name: p.name.getText(),
  237. type: p.type ? p.type.getText() : '',
  238. optional: !!p.questionToken,
  239. initializer: p.initializer && p.initializer.getText(),
  240. }));
  241. result.push({
  242. ...memberInfo,
  243. kind: 'method',
  244. parameters,
  245. });
  246. } else {
  247. result.push({
  248. ...memberInfo,
  249. kind: 'property',
  250. defaultValue,
  251. });
  252. }
  253. }
  254. }
  255. return result;
  256. }
  257. /**
  258. * Reads the @docsWeight JSDoc tag from the interface.
  259. */
  260. private getDeclarationWeight(statement: ValidDeclaration): number {
  261. let weight = 10;
  262. this.parseTags(statement, {
  263. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  264. });
  265. return weight;
  266. }
  267. /**
  268. * Reads the @description JSDoc tag from the interface.
  269. */
  270. private getDeclarationDescription(statement: ValidDeclaration): string {
  271. let description = '';
  272. this.parseTags(statement, {
  273. description: tag => (description += tag.comment),
  274. example: tag => (description += this.formatExampleCode(tag.comment)),
  275. });
  276. return this.restoreAtTokens(description);
  277. }
  278. /**
  279. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  280. */
  281. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  282. let category: string | undefined;
  283. this.parseTags(statement, {
  284. docsCategory: tag => (category = tag.comment || ''),
  285. });
  286. return this.kebabCase(category);
  287. }
  288. /**
  289. * Type guard for the types of statement which can ge processed by the doc generator.
  290. */
  291. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  292. return (
  293. ts.isInterfaceDeclaration(statement) ||
  294. ts.isTypeAliasDeclaration(statement) ||
  295. ts.isClassDeclaration(statement) ||
  296. ts.isEnumDeclaration(statement) ||
  297. ts.isFunctionDeclaration(statement)
  298. );
  299. }
  300. /**
  301. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  302. */
  303. private parseTags<T extends ts.Node>(
  304. node: T,
  305. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  306. ): void {
  307. const jsDocTags = ts.getJSDocTags(node);
  308. for (const tag of jsDocTags) {
  309. const tagName = tag.tagName.text;
  310. if (tagMatcher[tagName]) {
  311. tagMatcher[tagName](tag);
  312. }
  313. }
  314. }
  315. /**
  316. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  317. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  318. */
  319. private formatExampleCode(example: string = ''): string {
  320. return '\n\n*Example*\n\n' + example.replace(/\n\s+\*\s/g, '\n');
  321. }
  322. private kebabCase<T extends string | undefined>(input: T): T {
  323. if (input == null) {
  324. return input;
  325. }
  326. return input.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-').toLowerCase() as T;
  327. }
  328. /**
  329. * TypeScript from v3.5.1 interprets all '@' tokens in a tag comment as a new tag. This is a problem e.g.
  330. * when a plugin includes in it's description some text like "install the @vendure/some-plugin package". Here,
  331. * TypeScript will interpret "@vendure" as a JSDoc tag and remove it and all remaining text from the comment.
  332. *
  333. * The solution is to replace all escaped @ tokens ("\@") with a replacer string so that TypeScript treats them
  334. * as regular comment text, and then once it has parsed the statement, we replace them with the "@" character.
  335. */
  336. private replaceEscapedAtTokens(content: string): string {
  337. return content.replace(/\\@/g, this.atTokenPlaceholder);
  338. }
  339. /**
  340. * Restores "@" tokens which were replaced by the replaceEscapedAtTokens() method.
  341. */
  342. private restoreAtTokens(content: string): string {
  343. return content.replace(new RegExp(this.atTokenPlaceholder, 'g'), '@');
  344. }
  345. }