typescript-docs-parser.ts 14 KB

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