typescript-docs-renderer.ts 14 KB

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