typescript-docs-parser.ts 16 KB

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