typescript-docs-parser.ts 16 KB

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