typescript-docs-renderer.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. output += members
  150. .map(member => {
  151. if (member.kind === 'method') {
  152. const args = member.parameters
  153. .map(p => {
  154. return `${p.name}: ${p.type}`;
  155. })
  156. .join(', ');
  157. if (member.fullText === 'constructor') {
  158. return ` constructor(${args})`;
  159. } else {
  160. return ` ${member.fullText}(${args}) => ${member.type};`;
  161. }
  162. } else {
  163. return ` ${member.fullText}`;
  164. }
  165. })
  166. .join(`\n`);
  167. output += `\n}\n`;
  168. output += `\`\`\`\n`;
  169. return output;
  170. }
  171. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  172. const { fullText, members, type } = typeAliasInfo;
  173. let output = '';
  174. output += `\`\`\`TypeScript\n`;
  175. output += `type ${fullText} = `;
  176. if (members) {
  177. output += `{\n`;
  178. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  179. output += `\n}\n`;
  180. } else {
  181. output += type.getText() + `\n`;
  182. }
  183. output += `\`\`\`\n`;
  184. return output;
  185. }
  186. private renderEnumSignature(enumInfo: EnumInfo): string {
  187. const { fullText, members } = enumInfo;
  188. let output = '';
  189. output += `\`\`\`TypeScript\n`;
  190. output += `enum ${fullText} `;
  191. if (members) {
  192. output += `{\n`;
  193. output += members.map(member => {
  194. let line = member.description ? ` // ${member.description}\n` : '';
  195. line += ` ${member.fullText}`;
  196. return line;
  197. }).join(`\n`);
  198. output += `\n}\n`;
  199. }
  200. output += `\`\`\`\n`;
  201. return output;
  202. }
  203. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  204. const { fullText, parameters, type } = functionInfo;
  205. const args = parameters
  206. .map(p => {
  207. return `${p.name}: ${p.type}`;
  208. })
  209. .join(', ');
  210. let output = '';
  211. output += `\`\`\`TypeScript\n`;
  212. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  213. output += `\`\`\`\n`;
  214. return output;
  215. }
  216. private renderFunctionParams(params: MethodParameterInfo[], knownTypeMap: TypeMap, docsUrl: string): string {
  217. let output = '';
  218. for (const param of params) {
  219. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  220. output += `### ${param.name}\n\n`;
  221. output += `{{< member-info kind="parameter" type="${type}" >}}\n\n`;
  222. }
  223. return output;
  224. }
  225. private renderMembers(info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  226. const { members, title } = info;
  227. let output = '';
  228. for (const member of members || []) {
  229. let defaultParam = '';
  230. let type = '';
  231. if (member.kind === 'property') {
  232. type = this.renderType(member.type, knownTypeMap, docsUrl);
  233. defaultParam = member.defaultValue
  234. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  235. : '';
  236. } else {
  237. const args = member.parameters
  238. .map(p => {
  239. return `${p.name}: ${this.renderType(p.type, knownTypeMap, docsUrl)}`;
  240. })
  241. .join(', ');
  242. if (member.fullText === 'constructor') {
  243. type = `(${args}) => ${title}`;
  244. } else {
  245. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  246. }
  247. }
  248. output += `### ${member.name}\n\n`;
  249. output += `{{< member-info kind="${member.kind}" type="${type}" ${defaultParam}>}}\n\n`;
  250. output += `${this.renderDescription(member.description, knownTypeMap, docsUrl)}\n\n`;
  251. }
  252. return output;
  253. }
  254. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  255. const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
  256. return `{{< generation-info sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}">}}\n\n`;
  257. }
  258. /**
  259. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  260. * and known types (e.g. "ShippingMethod") into hyperlinks.
  261. */
  262. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  263. let typeText = type
  264. .trim()
  265. // encode HTML entities
  266. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  267. // remove newlines
  268. .replace(/\n/g, ' ');
  269. for (const [key, val] of knownTypeMap) {
  270. const re = new RegExp(`\\b${key}\\b`, 'g');
  271. const strippedIndex = val.replace(/\/_index$/, '');
  272. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}/'>${key}</a>`);
  273. }
  274. return typeText;
  275. }
  276. /**
  277. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  278. */
  279. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  280. for (const [key, val] of knownTypeMap) {
  281. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  282. description = description.replace(re, `<a href='${docsUrl}/${val}/'>${key}</a>`);
  283. }
  284. return description;
  285. }
  286. }