typescript-docs-parser.ts 15 KB

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