typescript-docs-parser.ts 16 KB

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