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