typescript-docs-parser.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. private readonly commentBlockEndTokenPlaceholder = '__EscapedCommentBlockEndToken__'
  21. /**
  22. * Parses the TypeScript files given by the filePaths array and returns the
  23. * parsed data structures ready for rendering.
  24. */
  25. parse(filePaths: string[]): DocsPage[] {
  26. const sourceFiles = filePaths.map(filePath => {
  27. return ts.createSourceFile(
  28. filePath,
  29. this.replaceEscapedTokens(fs.readFileSync(filePath).toString()),
  30. ts.ScriptTarget.ES2015,
  31. true,
  32. );
  33. });
  34. const statements = this.getStatementsWithSourceLocation(sourceFiles);
  35. const pageMap = statements
  36. .map(statement => {
  37. const info = this.parseDeclaration(
  38. statement.statement,
  39. statement.sourceFile,
  40. statement.sourceLine,
  41. );
  42. return info;
  43. })
  44. .filter(notNullOrUndefined)
  45. .reduce((pages, declaration) => {
  46. const pageTitle = declaration.page || declaration.title;
  47. const existingPage = pages.get(pageTitle);
  48. if (existingPage) {
  49. existingPage.declarations.push(declaration);
  50. } else {
  51. const normalizedTitle = this.kebabCase(pageTitle);
  52. const fileName = normalizedTitle === declaration.category ? '_index' : normalizedTitle;
  53. pages.set(pageTitle, {
  54. title: pageTitle,
  55. category: declaration.category,
  56. declarations: [declaration],
  57. fileName,
  58. });
  59. }
  60. return pages;
  61. }, new Map<string, DocsPage>());
  62. return Array.from(pageMap.values());
  63. }
  64. /**
  65. * Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
  66. * came from.
  67. */
  68. private getStatementsWithSourceLocation(
  69. sourceFiles: ts.SourceFile[],
  70. ): Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }> {
  71. return sourceFiles.reduce((st, sf) => {
  72. const statementsWithSources = sf.statements.map(statement => {
  73. const sourceFile = path.relative(path.join(__dirname, '..'), sf.fileName).replace(/\\/g, '/');
  74. const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
  75. return { statement, sourceFile, sourceLine };
  76. });
  77. return [...st, ...statementsWithSources];
  78. }, [] as Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }>);
  79. }
  80. /**
  81. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  82. */
  83. private parseDeclaration(
  84. statement: ts.Statement,
  85. sourceFile: string,
  86. sourceLine: number,
  87. ): ParsedDeclaration | undefined {
  88. if (!this.isValidDeclaration(statement)) {
  89. return;
  90. }
  91. const category = this.getDocsCategory(statement);
  92. if (category === undefined) {
  93. return;
  94. }
  95. let title: string;
  96. if (ts.isVariableStatement(statement)) {
  97. title = statement.declarationList.declarations[0].name.getText();
  98. } else {
  99. title = statement.name ? statement.name.getText() : 'anonymous';
  100. }
  101. const fullText = this.getDeclarationFullText(statement);
  102. const weight = this.getDeclarationWeight(statement);
  103. const description = this.getDeclarationDescription(statement);
  104. const docsPage = this.getDocsPage(statement);
  105. const since = this.getSince(statement);
  106. const experimental = this.getExperimental(statement);
  107. const packageName = this.getPackageName(sourceFile);
  108. const info = {
  109. packageName,
  110. sourceFile,
  111. sourceLine,
  112. fullText,
  113. title,
  114. weight,
  115. category,
  116. description,
  117. page: docsPage,
  118. since,
  119. experimental,
  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 interface 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. let experimental = false;
  250. if (ts.isConstructorDeclaration(member)) {
  251. fullText = 'constructor';
  252. } else if (ts.isMethodDeclaration(member)) {
  253. fullText = member.name.getText();
  254. } else if (ts.isGetAccessorDeclaration(member)) {
  255. fullText = `${member.name.getText()}: ${member.type ? member.type.getText() : 'void'}`;
  256. } else {
  257. fullText = member.getText();
  258. }
  259. this.parseTags(member, {
  260. description: comment => (description += comment || ''),
  261. example: comment => (description += this.formatExampleCode(comment)),
  262. default: comment => (defaultValue = comment || ''),
  263. internal: comment => (isInternal = true),
  264. since: comment => (since = comment || undefined),
  265. experimental: comment => (experimental = comment != null),
  266. });
  267. if (isInternal) {
  268. continue;
  269. }
  270. if (!ts.isEnumMember(member) && member.type) {
  271. type = member.type.getText();
  272. }
  273. const memberInfo: MemberInfo = {
  274. fullText,
  275. name,
  276. description: this.restoreTokens(description),
  277. type,
  278. modifiers,
  279. since,
  280. experimental,
  281. };
  282. if (
  283. ts.isMethodSignature(member) ||
  284. ts.isMethodDeclaration(member) ||
  285. ts.isConstructorDeclaration(member)
  286. ) {
  287. parameters = member.parameters.map(p => ({
  288. name: p.name.getText(),
  289. type: p.type ? p.type.getText() : '',
  290. optional: !!p.questionToken,
  291. initializer: p.initializer && p.initializer.getText(),
  292. }));
  293. result.push({
  294. ...memberInfo,
  295. kind: 'method',
  296. parameters,
  297. });
  298. } else {
  299. result.push({
  300. ...memberInfo,
  301. kind: 'property',
  302. defaultValue,
  303. });
  304. }
  305. }
  306. }
  307. return result;
  308. }
  309. private tagCommentText(tag: JSDocTag): string {
  310. if (!tag.comment) {
  311. return '';
  312. }
  313. if (typeof tag.comment === 'string') {
  314. return tag.comment;
  315. }
  316. return tag.comment.map(t => (t.kind === SyntaxKind.JSDocText ? t.text : t.getText())).join('');
  317. }
  318. /**
  319. * Reads the @docsWeight JSDoc tag from the interface.
  320. */
  321. private getDeclarationWeight(statement: ValidDeclaration): number {
  322. let weight = 10;
  323. this.parseTags(statement, {
  324. docsWeight: comment => (weight = Number.parseInt(comment || '10', 10)),
  325. });
  326. return weight;
  327. }
  328. private getDocsPage(statement: ValidDeclaration): string | undefined {
  329. let docsPage: string | undefined;
  330. this.parseTags(statement, {
  331. docsPage: comment => (docsPage = comment),
  332. });
  333. return docsPage;
  334. }
  335. /**
  336. * Reads the @since JSDoc tag
  337. */
  338. private getSince(statement: ValidDeclaration): string | undefined {
  339. let since: string | undefined;
  340. this.parseTags(statement, {
  341. since: comment => (since = comment),
  342. });
  343. return since;
  344. }
  345. /**
  346. * Reads the @experimental JSDoc tag
  347. */
  348. private getExperimental(statement: ValidDeclaration): boolean {
  349. let experimental = false;
  350. this.parseTags(statement, {
  351. experimental: comment => (experimental = comment != null),
  352. });
  353. return experimental;
  354. }
  355. /**
  356. * Reads the @description JSDoc tag from the interface.
  357. */
  358. private getDeclarationDescription(statement: ValidDeclaration): string {
  359. let description = '';
  360. this.parseTags(statement, {
  361. description: comment => (description += comment),
  362. example: comment => (description += this.formatExampleCode(comment)),
  363. });
  364. return this.restoreTokens(description);
  365. }
  366. /**
  367. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  368. */
  369. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  370. let category: string | undefined;
  371. this.parseTags(statement, {
  372. docsCategory: comment => (category = comment || ''),
  373. });
  374. return this.kebabCase(category);
  375. }
  376. /**
  377. * Type guard for the types of statement which can ge processed by the doc generator.
  378. */
  379. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  380. return (
  381. ts.isInterfaceDeclaration(statement) ||
  382. ts.isTypeAliasDeclaration(statement) ||
  383. ts.isClassDeclaration(statement) ||
  384. ts.isEnumDeclaration(statement) ||
  385. ts.isFunctionDeclaration(statement) ||
  386. ts.isVariableStatement(statement)
  387. );
  388. }
  389. /**
  390. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  391. */
  392. private parseTags<T extends ts.Node>(
  393. node: T,
  394. tagMatcher: { [tagName: string]: (tagComment: string) => void },
  395. ): void {
  396. const jsDocTags = ts.getJSDocTags(node);
  397. for (const tag of jsDocTags) {
  398. const tagName = tag.tagName.text;
  399. if (tagMatcher[tagName]) {
  400. tagMatcher[tagName](this.tagCommentText(tag));
  401. }
  402. }
  403. }
  404. /**
  405. * Ensure all the code examples use the unix-style line separators.
  406. */
  407. private formatExampleCode(example: string = ''): string {
  408. return '\n\n*Example*\n\n' + example.replace(/\r/g, '');
  409. }
  410. private kebabCase<T extends string | undefined>(input: T): T {
  411. if (input == null) {
  412. return input;
  413. }
  414. return input
  415. .replace(/([a-z])([A-Z])/g, '$1-$2')
  416. .replace(/\s+/g, '-')
  417. .toLowerCase() as T;
  418. }
  419. /**
  420. * TypeScript from v3.5.1 interprets all '@' tokens in a tag comment as a new tag. This is a problem e.g.
  421. * when a plugin includes in its description some text like "install the @vendure/some-plugin package". Here,
  422. * TypeScript will interpret "@vendure" as a JSDoc tag and remove it and all remaining text from the comment.
  423. *
  424. * The solution is to replace all escaped @ tokens ("\@") with a replacer string so that TypeScript treats them
  425. * as regular comment text, and then once it has parsed the statement, we replace them with the "@" character.
  426. *
  427. * Similarly, '/*' is interpreted as end of a comment block. However, it can be useful to specify a globstar
  428. * pattern in descriptions and therefore it is supported as long as the leading '/' is escaped ("\/").
  429. */
  430. private replaceEscapedTokens(content: string): string {
  431. return content.replace(/\\@/g, this.atTokenPlaceholder).replace(/\\\/\*/g, this.commentBlockEndTokenPlaceholder);
  432. }
  433. /**
  434. * Restores "@" and "/*" tokens which were replaced by the replaceEscapedTokens() method.
  435. */
  436. private restoreTokens(content: string): string {
  437. return content.replace(new RegExp(this.atTokenPlaceholder, 'g'), '@').replace(new RegExp(this.commentBlockEndTokenPlaceholder, 'g'), '/*');
  438. }
  439. }