typescript-docs-parser.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 { normalizeForUrlPart } from './docgen-utils';
  6. import {
  7. DocsPage,
  8. MemberInfo,
  9. MethodInfo,
  10. MethodParameterInfo,
  11. ParsedDeclaration,
  12. PropertyInfo,
  13. ValidDeclaration,
  14. } from './typescript-docgen-types';
  15. /**
  16. * Parses TypeScript source files into data structures which can then be rendered into
  17. * markdown for documentation.
  18. */
  19. export class TypescriptDocsParser {
  20. private readonly atTokenPlaceholder = '__EscapedAtToken__';
  21. private readonly commentBlockEndTokenPlaceholder = '__EscapedCommentBlockEndToken__';
  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.replaceEscapedTokens(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 = normalizeForUrlPart(pageTitle);
  53. const categoryLastPart = declaration.category.split('/').pop();
  54. const fileName = normalizedTitle === categoryLastPart ? 'index' : normalizedTitle;
  55. pages.set(pageTitle, {
  56. title: pageTitle,
  57. category: declaration.category.split('/'),
  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 experimental = this.getExperimental(statement);
  109. const packageName = this.getPackageName(sourceFile);
  110. const info = {
  111. packageName,
  112. sourceFile,
  113. sourceLine,
  114. fullText,
  115. title,
  116. weight,
  117. category,
  118. description,
  119. page: docsPage,
  120. since,
  121. experimental,
  122. };
  123. if (ts.isInterfaceDeclaration(statement)) {
  124. return {
  125. ...info,
  126. kind: 'interface',
  127. extendsClause: this.getHeritageClause(statement, ts.SyntaxKind.ExtendsKeyword),
  128. members: this.parseMembers(statement.members),
  129. };
  130. } else if (ts.isTypeAliasDeclaration(statement)) {
  131. return {
  132. ...info,
  133. type: statement.type,
  134. kind: 'typeAlias',
  135. members: ts.isTypeLiteralNode(statement.type)
  136. ? this.parseMembers(statement.type.members)
  137. : undefined,
  138. };
  139. } else if (ts.isClassDeclaration(statement)) {
  140. return {
  141. ...info,
  142. kind: 'class',
  143. members: this.parseMembers(statement.members),
  144. extendsClause: this.getHeritageClause(statement, ts.SyntaxKind.ExtendsKeyword),
  145. implementsClause: this.getHeritageClause(statement, ts.SyntaxKind.ImplementsKeyword),
  146. };
  147. } else if (ts.isEnumDeclaration(statement)) {
  148. return {
  149. ...info,
  150. kind: 'enum' as const,
  151. members: this.parseMembers(statement.members) as PropertyInfo[],
  152. };
  153. } else if (ts.isFunctionDeclaration(statement)) {
  154. const parameters = statement.parameters.map(p => ({
  155. name: p.name.getText(),
  156. type: p.type ? p.type.getText() : '',
  157. optional: !!p.questionToken,
  158. initializer: p.initializer && p.initializer.getText(),
  159. }));
  160. return {
  161. ...info,
  162. kind: 'function',
  163. parameters,
  164. type: statement.type,
  165. };
  166. } else if (ts.isVariableStatement(statement)) {
  167. return {
  168. ...info,
  169. kind: 'variable',
  170. };
  171. }
  172. }
  173. /**
  174. * Returns the text of any "extends" or "implements" clause of a class or interface.
  175. */
  176. private getHeritageClause(
  177. statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
  178. kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
  179. ): HeritageClause | undefined {
  180. const { heritageClauses } = statement;
  181. if (!heritageClauses) {
  182. return;
  183. }
  184. const clause = heritageClauses.find(cl => cl.token === kind);
  185. if (!clause) {
  186. return;
  187. }
  188. return clause;
  189. }
  190. /**
  191. * Returns the declaration name plus any type parameters.
  192. */
  193. private getDeclarationFullText(declaration: ValidDeclaration): string {
  194. let name: string;
  195. if (ts.isVariableStatement(declaration)) {
  196. name = declaration.declarationList.declarations[0].name.getText();
  197. } else {
  198. name = declaration.name ? declaration.name.getText() : 'anonymous';
  199. }
  200. let typeParams = '';
  201. if (
  202. !ts.isEnumDeclaration(declaration) &&
  203. !ts.isVariableStatement(declaration) &&
  204. declaration.typeParameters
  205. ) {
  206. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  207. }
  208. return name + typeParams;
  209. }
  210. private getPackageName(sourceFile: string): string {
  211. const matches = sourceFile.match(/\/packages\/([^/]+)\//);
  212. if (matches) {
  213. return `@vendure/${matches[1]}`;
  214. } else {
  215. return '';
  216. }
  217. }
  218. /**
  219. * Parses an array of interface members into a simple object which can be rendered into markdown.
  220. */
  221. private parseMembers(
  222. members: ts.NodeArray<ts.TypeElement | ts.ClassElement | ts.EnumMember>,
  223. ): Array<PropertyInfo | MethodInfo> {
  224. const result: Array<PropertyInfo | MethodInfo> = [];
  225. for (const member of members) {
  226. const modifiers = member.modifiers ? member.modifiers.map(m => m.getText()) : [];
  227. const isPrivate = modifiers.includes('private');
  228. if (
  229. !isPrivate &&
  230. (ts.isPropertySignature(member) ||
  231. ts.isMethodSignature(member) ||
  232. ts.isPropertyDeclaration(member) ||
  233. ts.isMethodDeclaration(member) ||
  234. ts.isConstructorDeclaration(member) ||
  235. ts.isEnumMember(member) ||
  236. ts.isGetAccessorDeclaration(member) ||
  237. ts.isIndexSignatureDeclaration(member))
  238. ) {
  239. const name = member.name
  240. ? member.name.getText()
  241. : ts.isIndexSignatureDeclaration(member)
  242. ? '[index]'
  243. : 'constructor';
  244. let description = '';
  245. let type = '';
  246. let defaultValue = '';
  247. let parameters: MethodParameterInfo[] = [];
  248. let fullText = '';
  249. let isInternal = false;
  250. let since: string | undefined;
  251. let experimental = false;
  252. if (ts.isConstructorDeclaration(member)) {
  253. fullText = 'constructor';
  254. } else if (ts.isMethodDeclaration(member)) {
  255. fullText = member.name.getText();
  256. } else if (ts.isGetAccessorDeclaration(member)) {
  257. fullText = `${member.name.getText()}: ${member.type ? member.type.getText() : 'void'}`;
  258. } else {
  259. fullText = member.getText();
  260. }
  261. this.parseTags(member, {
  262. description: comment => (description += comment || ''),
  263. example: comment => (description += this.formatExampleCode(comment)),
  264. default: comment => (defaultValue = comment || ''),
  265. internal: comment => (isInternal = true),
  266. since: comment => (since = comment || undefined),
  267. experimental: comment => (experimental = comment != null),
  268. });
  269. if (isInternal) {
  270. continue;
  271. }
  272. if (!ts.isEnumMember(member) && member.type) {
  273. type = member.type.getText();
  274. }
  275. const memberInfo: MemberInfo = {
  276. fullText,
  277. name,
  278. description: this.restoreTokens(description),
  279. type,
  280. modifiers,
  281. since,
  282. experimental,
  283. };
  284. if (
  285. ts.isMethodSignature(member) ||
  286. ts.isMethodDeclaration(member) ||
  287. ts.isConstructorDeclaration(member)
  288. ) {
  289. parameters = member.parameters.map(p => ({
  290. name: p.name.getText(),
  291. type: p.type ? p.type.getText() : '',
  292. optional: !!p.questionToken,
  293. initializer: p.initializer && p.initializer.getText(),
  294. }));
  295. result.push({
  296. ...memberInfo,
  297. kind: 'method',
  298. parameters,
  299. });
  300. } else {
  301. result.push({
  302. ...memberInfo,
  303. kind: 'property',
  304. defaultValue,
  305. });
  306. }
  307. }
  308. }
  309. return result;
  310. }
  311. private tagCommentText(tag: JSDocTag): string {
  312. if (!tag.comment) {
  313. return '';
  314. }
  315. if (typeof tag.comment === 'string') {
  316. return tag.comment;
  317. }
  318. return tag.comment.map(t => (t.kind === SyntaxKind.JSDocText ? t.text : t.getText())).join('');
  319. }
  320. /**
  321. * Reads the @docsWeight JSDoc tag from the interface.
  322. */
  323. private getDeclarationWeight(statement: ValidDeclaration): number {
  324. let weight = 10;
  325. this.parseTags(statement, {
  326. docsWeight: comment => (weight = Number.parseInt(comment || '10', 10)),
  327. });
  328. return weight;
  329. }
  330. private getDocsPage(statement: ValidDeclaration): string | undefined {
  331. let docsPage: string | undefined;
  332. this.parseTags(statement, {
  333. docsPage: comment => (docsPage = comment),
  334. });
  335. return docsPage;
  336. }
  337. /**
  338. * Reads the @since JSDoc tag
  339. */
  340. private getSince(statement: ValidDeclaration): string | undefined {
  341. let since: string | undefined;
  342. this.parseTags(statement, {
  343. since: comment => (since = comment),
  344. });
  345. return since;
  346. }
  347. /**
  348. * Reads the @experimental JSDoc tag
  349. */
  350. private getExperimental(statement: ValidDeclaration): boolean {
  351. let experimental = false;
  352. this.parseTags(statement, {
  353. experimental: comment => (experimental = comment != null),
  354. });
  355. return experimental;
  356. }
  357. /**
  358. * Reads the @description JSDoc tag from the interface.
  359. */
  360. private getDeclarationDescription(statement: ValidDeclaration): string {
  361. let description = '';
  362. this.parseTags(statement, {
  363. description: comment => (description += comment),
  364. example: comment => (description += this.formatExampleCode(comment)),
  365. });
  366. return this.restoreTokens(description);
  367. }
  368. /**
  369. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  370. */
  371. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  372. let category: string | undefined;
  373. this.parseTags(statement, {
  374. docsCategory: comment => (category = comment || ''),
  375. });
  376. return normalizeForUrlPart(category);
  377. }
  378. /**
  379. * Type guard for the types of statement which can ge processed by the doc generator.
  380. */
  381. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  382. return (
  383. ts.isInterfaceDeclaration(statement) ||
  384. ts.isTypeAliasDeclaration(statement) ||
  385. ts.isClassDeclaration(statement) ||
  386. ts.isEnumDeclaration(statement) ||
  387. ts.isFunctionDeclaration(statement) ||
  388. ts.isVariableStatement(statement)
  389. );
  390. }
  391. /**
  392. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  393. */
  394. private parseTags<T extends ts.Node>(
  395. node: T,
  396. tagMatcher: { [tagName: string]: (tagComment: string) => void },
  397. ): void {
  398. const jsDocTags = ts.getJSDocTags(node);
  399. for (const tag of jsDocTags) {
  400. const tagName = tag.tagName.text;
  401. if (tagMatcher[tagName]) {
  402. tagMatcher[tagName](this.tagCommentText(tag));
  403. }
  404. }
  405. }
  406. /**
  407. * Ensure all the code examples use the unix-style line separators.
  408. */
  409. private formatExampleCode(example: string = ''): string {
  410. return '\n\n*Example*\n\n' + example.replace(/\r/g, '');
  411. }
  412. /**
  413. * TypeScript from v3.5.1 interprets all '@' tokens in a tag comment as a new tag. This is a problem e.g.
  414. * when a plugin includes in its description some text like "install the @vendure/some-plugin package". Here,
  415. * TypeScript will interpret "@vendure" as a JSDoc tag and remove it and all remaining text from the comment.
  416. *
  417. * The solution is to replace all escaped @ tokens ("\@") with a replacer string so that TypeScript treats them
  418. * as regular comment text, and then once it has parsed the statement, we replace them with the "@" character.
  419. *
  420. * Similarly, '/*' is interpreted as end of a comment block. However, it can be useful to specify a globstar
  421. * pattern in descriptions and therefore it is supported as long as the leading '/' is escaped ("\/").
  422. */
  423. private replaceEscapedTokens(content: string): string {
  424. return content
  425. .replace(/\\@/g, this.atTokenPlaceholder)
  426. .replace(/\\\/\*/g, this.commentBlockEndTokenPlaceholder);
  427. }
  428. /**
  429. * Restores "@" and "/*" tokens which were replaced by the replaceEscapedTokens() method.
  430. */
  431. private restoreTokens(content: string): string {
  432. return content
  433. .replace(new RegExp(this.atTokenPlaceholder, 'g'), '@')
  434. .replace(new RegExp(this.commentBlockEndTokenPlaceholder, 'g'), '/*');
  435. }
  436. }