1
0

typescript-docs-renderer.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. // tslint:disable:no-console
  2. import fs from 'fs-extra';
  3. import klawSync from 'klaw-sync';
  4. import path from 'path';
  5. import ts from 'typescript';
  6. import { assertNever } from '../../packages/common/src/shared-utils';
  7. import { deleteGeneratedDocs, generateFrontMatter } from './docgen-utils';
  8. import { ClassInfo, DeclarationInfo, InterfaceInfo, ParsedDeclaration, TypeAliasInfo, TypeMap } from './typescript-docgen-types';
  9. export class TypescriptDocsRenderer {
  10. render(parsedDeclarations: ParsedDeclaration[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  11. let generatedCount = 0;
  12. if (!fs.existsSync(outputPath)) {
  13. fs.mkdirs(outputPath);
  14. }
  15. for (const info of parsedDeclarations) {
  16. let markdown = '';
  17. switch (info.kind) {
  18. case 'interface':
  19. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  20. break;
  21. case 'typeAlias':
  22. markdown = this.renderTypeAlias(info, typeMap, docsUrl);
  23. break;
  24. case 'class':
  25. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  26. break;
  27. default:
  28. assertNever(info);
  29. }
  30. const categoryDir = path.join(outputPath, info.category);
  31. const indexFile = path.join(categoryDir, '_index.md');
  32. if (!fs.existsSync(categoryDir)) {
  33. fs.mkdirs(categoryDir);
  34. }
  35. if (!fs.existsSync(indexFile)) {
  36. const indexFileContent = generateFrontMatter(info.category, 10, false) + `\n\n# ${info.category}`;
  37. fs.writeFileSync(indexFile, indexFileContent);
  38. generatedCount++;
  39. }
  40. fs.writeFileSync(path.join(categoryDir, info.fileName + '.md'), markdown);
  41. generatedCount++;
  42. }
  43. return generatedCount;
  44. }
  45. /**
  46. * Render the interface to a markdown string.
  47. */
  48. private renderInterfaceOrClass(info: InterfaceInfo | ClassInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  49. const { title, weight, category, description, members } = info;
  50. let output = '';
  51. output += generateFrontMatter(title, weight);
  52. output += `\n\n# ${title}\n\n`;
  53. output += this.renderGenerationInfoShortcode(info);
  54. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  55. output += `## Signature\n\n`;
  56. output += info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  57. output += `## Members\n\n`;
  58. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  59. return output;
  60. }
  61. /**
  62. * Render the type alias to a markdown string.
  63. */
  64. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  65. const { title, weight, description, type, fullText } = typeAliasInfo;
  66. let output = '';
  67. output += generateFrontMatter(title, weight);
  68. output += `\n\n# ${title}\n\n`;
  69. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  70. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  71. output += `## Signature\n\n`;
  72. output += this.renderTypeAliasSignature(typeAliasInfo);
  73. if (typeAliasInfo.members) {
  74. output += `## Members\n\n`;
  75. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  76. }
  77. return output;
  78. }
  79. /**
  80. * Generates a markdown code block string for the interface signature.
  81. */
  82. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  83. const { fullText, members } = interfaceInfo;
  84. let output = '';
  85. output += `\`\`\`TypeScript\n`;
  86. output += `interface ${fullText} `;
  87. if (interfaceInfo.extends) {
  88. output += interfaceInfo.extends + ' ';
  89. }
  90. output += `{\n`;
  91. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  92. output += `\n}\n`;
  93. output += `\`\`\`\n`;
  94. return output;
  95. }
  96. private renderClassSignature(classInfo: ClassInfo): string {
  97. const { fullText, members } = classInfo;
  98. let output = '';
  99. output += `\`\`\`TypeScript\n`;
  100. output += `class ${fullText} `;
  101. if (classInfo.extends) {
  102. output += classInfo.extends + ' ';
  103. }
  104. if (classInfo.implements) {
  105. output += classInfo.implements + ' ';
  106. }
  107. output += `{\n`;
  108. output += members
  109. .map(member => {
  110. if (member.kind === 'method') {
  111. const args = member.parameters
  112. .map(p => {
  113. return `${p.name}: ${p.type}`;
  114. })
  115. .join(', ');
  116. if (member.fullText === 'constructor') {
  117. return ` constructor(${args})`;
  118. } else {
  119. return ` ${member.fullText}(${args}) => ${member.type};`;
  120. }
  121. } else {
  122. return ` ${member.fullText}`;
  123. }
  124. })
  125. .join(`\n`);
  126. output += `\n}\n`;
  127. output += `\`\`\`\n`;
  128. return output;
  129. }
  130. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  131. const { fullText, members, type } = typeAliasInfo;
  132. let output = '';
  133. output += `\`\`\`TypeScript\n`;
  134. output += `type ${fullText} = `;
  135. if (members) {
  136. output += `{\n`;
  137. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  138. output += `\n}\n`;
  139. } else {
  140. output += type.getText() + `\n`;
  141. }
  142. output += `\`\`\`\n`;
  143. return output;
  144. }
  145. private renderMembers(info: InterfaceInfo | ClassInfo | TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  146. const { members, title } = info;
  147. let output = '';
  148. for (const member of members || []) {
  149. let defaultParam = '';
  150. let type = '';
  151. if (member.kind === 'property') {
  152. type = this.renderType(member.type, knownTypeMap, docsUrl);
  153. defaultParam = member.defaultValue
  154. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  155. : '';
  156. } else {
  157. const args = member.parameters
  158. .map(p => {
  159. return `${p.name}: ${this.renderType(p.type, knownTypeMap, docsUrl)}`;
  160. })
  161. .join(', ');
  162. if (member.fullText === 'constructor') {
  163. type = `(${args}) => ${title}`;
  164. } else {
  165. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  166. }
  167. }
  168. output += `### ${member.name}\n\n`;
  169. output += `{{< member-info kind="${member.kind}" type="${type}" ${defaultParam}>}}\n\n`;
  170. output += `${this.renderDescription(member.description, knownTypeMap, docsUrl)}\n\n`;
  171. }
  172. return output;
  173. }
  174. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  175. return `{{< generation-info sourceFile="${info.sourceFile}" sourceLine="${info.sourceLine}">}}\n\n`;
  176. }
  177. /**
  178. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  179. * and known types (e.g. "ShippingMethod") into hyperlinks.
  180. */
  181. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  182. let typeText = type
  183. .trim()
  184. // encode HTML entities
  185. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  186. // remove newlines
  187. .replace(/\n/g, ' ');
  188. for (const [key, val] of knownTypeMap) {
  189. const re = new RegExp(`\\b${key}\\b`, 'g');
  190. typeText = typeText.replace(re, `<a href='${docsUrl}/${val}/'>${key}</a>`);
  191. }
  192. return typeText;
  193. }
  194. /**
  195. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  196. */
  197. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  198. for (const [key, val] of knownTypeMap) {
  199. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  200. description = description.replace(re, `<a href='${docsUrl}/${val}/'>${key}</a>`);
  201. }
  202. return description;
  203. }
  204. }