typescript-docs-renderer.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 {
  9. ClassInfo,
  10. DeclarationInfo,
  11. EnumInfo,
  12. FunctionInfo,
  13. InterfaceInfo, MethodParameterInfo,
  14. ParsedDeclaration,
  15. TypeAliasInfo,
  16. TypeMap,
  17. } from './typescript-docgen-types';
  18. export class TypescriptDocsRenderer {
  19. render(parsedDeclarations: ParsedDeclaration[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  20. let generatedCount = 0;
  21. if (!fs.existsSync(outputPath)) {
  22. fs.mkdirs(outputPath);
  23. }
  24. for (const info of parsedDeclarations) {
  25. let markdown = '';
  26. switch (info.kind) {
  27. case 'interface':
  28. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  29. break;
  30. case 'typeAlias':
  31. markdown = this.renderTypeAlias(info, typeMap, docsUrl);
  32. break;
  33. case 'class':
  34. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  35. break;
  36. case 'enum':
  37. markdown = this.renderEnum(info, typeMap, docsUrl);
  38. break;
  39. case 'function':
  40. markdown = this.renderFunction(info, typeMap, docsUrl);
  41. break;
  42. default:
  43. assertNever(info);
  44. }
  45. const categoryDir = path.join(outputPath, info.category);
  46. const indexFile = path.join(categoryDir, '_index.md');
  47. if (!fs.existsSync(categoryDir)) {
  48. fs.mkdirsSync(categoryDir);
  49. }
  50. if (!fs.existsSync(indexFile)) {
  51. const indexFileContent = generateFrontMatter(info.category, 10, false) + `\n\n# ${info.category}`;
  52. fs.writeFileSync(indexFile, indexFileContent);
  53. generatedCount++;
  54. }
  55. fs.writeFileSync(path.join(categoryDir, info.fileName + '.md'), markdown);
  56. generatedCount++;
  57. }
  58. return generatedCount;
  59. }
  60. /**
  61. * Render the interface to a markdown string.
  62. */
  63. private renderInterfaceOrClass(info: InterfaceInfo | ClassInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  64. const { title, weight, category, description, members } = info;
  65. let output = '';
  66. output += generateFrontMatter(title, weight);
  67. output += `\n\n# ${title}\n\n`;
  68. output += this.renderGenerationInfoShortcode(info);
  69. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  70. output += `## Signature\n\n`;
  71. output += info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  72. output += `## Members\n\n`;
  73. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  74. return output;
  75. }
  76. /**
  77. * Render the type alias to a markdown string.
  78. */
  79. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  80. const { title, weight, description, type, fullText } = typeAliasInfo;
  81. let output = '';
  82. output += generateFrontMatter(title, weight);
  83. output += `\n\n# ${title}\n\n`;
  84. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  85. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  86. output += `## Signature\n\n`;
  87. output += this.renderTypeAliasSignature(typeAliasInfo);
  88. if (typeAliasInfo.members) {
  89. output += `## Members\n\n`;
  90. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  91. }
  92. return output;
  93. }
  94. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  95. const { title, weight, description, fullText } = enumInfo;
  96. let output = '';
  97. output += generateFrontMatter(title, weight);
  98. output += `\n\n# ${title}\n\n`;
  99. output += this.renderGenerationInfoShortcode(enumInfo);
  100. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  101. output += `## Signature\n\n`;
  102. output += this.renderEnumSignature(enumInfo);
  103. return output;
  104. }
  105. private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  106. const { title, weight, description, fullText, parameters } = functionInfo;
  107. let output = '';
  108. output += generateFrontMatter(title, weight);
  109. output += `\n\n# ${title}\n\n`;
  110. output += this.renderGenerationInfoShortcode(functionInfo);
  111. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  112. output += `## Signature\n\n`;
  113. output += this.renderFunctionSignature(functionInfo, knownTypeMap);
  114. if (parameters.length) {
  115. output += `## Parameters\n\n`;
  116. output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
  117. }
  118. return output;
  119. }
  120. /**
  121. * Generates a markdown code block string for the interface signature.
  122. */
  123. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  124. const { fullText, members } = interfaceInfo;
  125. let output = '';
  126. output += `\`\`\`TypeScript\n`;
  127. output += `interface ${fullText} `;
  128. if (interfaceInfo.extends) {
  129. output += interfaceInfo.extends + ' ';
  130. }
  131. output += `{\n`;
  132. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  133. output += `\n}\n`;
  134. output += `\`\`\`\n`;
  135. return output;
  136. }
  137. private renderClassSignature(classInfo: ClassInfo): string {
  138. const { fullText, members } = classInfo;
  139. let output = '';
  140. output += `\`\`\`TypeScript\n`;
  141. output += `class ${fullText} `;
  142. if (classInfo.extends) {
  143. output += classInfo.extends + ' ';
  144. }
  145. if (classInfo.implements) {
  146. output += classInfo.implements + ' ';
  147. }
  148. output += `{\n`;
  149. const renderModifiers = (modifiers: string[]) => modifiers.length ? modifiers.join(' ') + ' ' : '';
  150. output += members
  151. .map(member => {
  152. if (member.kind === 'method') {
  153. const args = member.parameters
  154. .map(p => {
  155. return `${p.name}: ${p.type}`;
  156. })
  157. .join(', ');
  158. if (member.fullText === 'constructor') {
  159. return ` constructor(${args})`;
  160. } else {
  161. return ` ${renderModifiers(member.modifiers)}${member.fullText}(${args}) => ${member.type};`;
  162. }
  163. } else {
  164. return ` ${renderModifiers(member.modifiers)}${member.fullText}`;
  165. }
  166. })
  167. .join(`\n`);
  168. output += `\n}\n`;
  169. output += `\`\`\`\n`;
  170. return output;
  171. }
  172. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  173. const { fullText, members, type } = typeAliasInfo;
  174. let output = '';
  175. output += `\`\`\`TypeScript\n`;
  176. output += `type ${fullText} = `;
  177. if (members) {
  178. output += `{\n`;
  179. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  180. output += `\n}\n`;
  181. } else {
  182. output += type.getText() + `\n`;
  183. }
  184. output += `\`\`\`\n`;
  185. return output;
  186. }
  187. private renderEnumSignature(enumInfo: EnumInfo): string {
  188. const { fullText, members } = enumInfo;
  189. let output = '';
  190. output += `\`\`\`TypeScript\n`;
  191. output += `enum ${fullText} `;
  192. if (members) {
  193. output += `{\n`;
  194. output += members.map(member => {
  195. let line = member.description ? ` // ${member.description}\n` : '';
  196. line += ` ${member.fullText}`;
  197. return line;
  198. }).join(`\n`);
  199. output += `\n}\n`;
  200. }
  201. output += `\`\`\`\n`;
  202. return output;
  203. }
  204. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  205. const { fullText, parameters, type } = functionInfo;
  206. const args = parameters
  207. .map(p => {
  208. return `${p.name}: ${p.type}`;
  209. })
  210. .join(', ');
  211. let output = '';
  212. output += `\`\`\`TypeScript\n`;
  213. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  214. output += `\`\`\`\n`;
  215. return output;
  216. }
  217. private renderFunctionParams(params: MethodParameterInfo[], knownTypeMap: TypeMap, docsUrl: string): string {
  218. let output = '';
  219. for (const param of params) {
  220. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  221. output += `### ${param.name}\n\n`;
  222. output += `{{< member-info kind="parameter" type="${type}" >}}\n\n`;
  223. }
  224. return output;
  225. }
  226. private renderMembers(info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  227. const { members, title } = info;
  228. let output = '';
  229. for (const member of members || []) {
  230. let defaultParam = '';
  231. let type = '';
  232. if (member.kind === 'property') {
  233. type = this.renderType(member.type, knownTypeMap, docsUrl);
  234. defaultParam = member.defaultValue
  235. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  236. : '';
  237. } else {
  238. const args = member.parameters
  239. .map(p => {
  240. return `${p.name}: ${this.renderType(p.type, knownTypeMap, docsUrl)}`;
  241. })
  242. .join(', ');
  243. if (member.fullText === 'constructor') {
  244. type = `(${args}) => ${title}`;
  245. } else {
  246. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  247. }
  248. }
  249. output += `### ${member.name}\n\n`;
  250. output += `{{< member-info kind="${[...member.modifiers, member.kind].join(' ')}" type="${type}" ${defaultParam}>}}\n\n`;
  251. output += `${this.renderDescription(member.description, knownTypeMap, docsUrl)}\n\n`;
  252. }
  253. return output;
  254. }
  255. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  256. const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
  257. return `{{< generation-info sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}">}}\n\n`;
  258. }
  259. /**
  260. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  261. * and known types (e.g. "ShippingMethod") into hyperlinks.
  262. */
  263. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  264. let typeText = type
  265. .trim()
  266. // encode HTML entities
  267. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  268. // remove newlines
  269. .replace(/\n/g, ' ');
  270. for (const [key, val] of knownTypeMap) {
  271. const re = new RegExp(`\\b${key}\\b`, 'g');
  272. const strippedIndex = val.replace(/\/_index$/, '');
  273. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}/'>${key}</a>`);
  274. }
  275. return typeText;
  276. }
  277. /**
  278. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  279. */
  280. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  281. for (const [key, val] of knownTypeMap) {
  282. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  283. description = description.replace(re, `<a href='${docsUrl}/${val}/'>${key}</a>`);
  284. }
  285. return description;
  286. }
  287. }