typescript-docs-renderer.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /* eslint-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. const INDENT = ' ';
  20. export class TypescriptDocsRenderer {
  21. render(pages: DocsPage[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  22. let generatedCount = 0;
  23. if (!fs.existsSync(outputPath)) {
  24. fs.mkdirSync(outputPath);
  25. }
  26. for (const page of pages) {
  27. let markdown = '';
  28. markdown += generateFrontMatter(page.title, 10);
  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. }
  54. const categoryDir = path.join(outputPath, ...page.category);
  55. if (!fs.existsSync(categoryDir)) {
  56. fs.mkdirsSync(categoryDir);
  57. }
  58. const pathParts = [];
  59. for (const subCategory of page.category) {
  60. pathParts.push(subCategory);
  61. const indexFile = path.join(outputPath, ...pathParts, 'index.md');
  62. if (!fs.existsSync(indexFile)) {
  63. const indexFileContent =
  64. generateFrontMatter(subCategory, 10, false) + `\n\n# ${subCategory}`;
  65. fs.writeFileSync(indexFile, indexFileContent);
  66. generatedCount++;
  67. }
  68. }
  69. fs.writeFileSync(path.join(categoryDir, page.fileName + '.md'), markdown);
  70. generatedCount++;
  71. }
  72. return generatedCount;
  73. }
  74. /**
  75. * Render the interface to a markdown string.
  76. */
  77. private renderInterfaceOrClass(
  78. info: InterfaceInfo | ClassInfo,
  79. knownTypeMap: TypeMap,
  80. docsUrl: string,
  81. ): string {
  82. const { title, weight, category, description, members } = info;
  83. let output = '';
  84. output += `\n\n## ${title}\n\n`;
  85. output += this.renderGenerationInfoShortcode(info);
  86. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  87. output +=
  88. info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  89. if (info.extendsClause) {
  90. output += '* Extends: ';
  91. output += `${this.renderHeritageClause(info.extendsClause, knownTypeMap, docsUrl)}\n`;
  92. }
  93. if (info.kind === 'class' && info.implementsClause) {
  94. output += '* Implements: ';
  95. output += `${this.renderHeritageClause(info.implementsClause, knownTypeMap, docsUrl)}\n`;
  96. }
  97. if (info.members && info.members.length) {
  98. output += '\n<div className="members-wrapper">\n';
  99. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  100. output += '\n\n</div>\n';
  101. }
  102. return output;
  103. }
  104. /**
  105. * Render the type alias to a markdown string.
  106. */
  107. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  108. const { title, weight, description, type, fullText } = typeAliasInfo;
  109. let output = '';
  110. output += `\n\n## ${title}\n\n`;
  111. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  112. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  113. output += this.renderTypeAliasSignature(typeAliasInfo);
  114. if (typeAliasInfo.members && typeAliasInfo.members.length) {
  115. output += '\n<div className="members-wrapper">\n';
  116. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  117. output += '\n\n</div>\n';
  118. }
  119. return output;
  120. }
  121. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  122. const { title, weight, description, fullText } = enumInfo;
  123. let output = '';
  124. output += `\n\n## ${title}\n\n`;
  125. output += this.renderGenerationInfoShortcode(enumInfo);
  126. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  127. output += this.renderEnumSignature(enumInfo);
  128. return output;
  129. }
  130. private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  131. const { title, weight, description, fullText, parameters } = functionInfo;
  132. let output = '';
  133. output += `\n\n## ${title}\n\n`;
  134. output += this.renderGenerationInfoShortcode(functionInfo);
  135. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  136. output += this.renderFunctionSignature(functionInfo, knownTypeMap);
  137. if (parameters.length) {
  138. output += 'Parameters\n\n';
  139. output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
  140. }
  141. return output;
  142. }
  143. private renderVariable(variableInfo: VariableInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  144. const { title, weight, description, fullText } = variableInfo;
  145. let output = '';
  146. output += `\n\n## ${title}\n\n`;
  147. output += this.renderGenerationInfoShortcode(variableInfo);
  148. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  149. return output;
  150. }
  151. /**
  152. * Generates a markdown code block string for the interface signature.
  153. */
  154. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  155. const { fullText, members } = interfaceInfo;
  156. let output = '';
  157. output += '```ts title="Signature"\n';
  158. output += `interface ${fullText} `;
  159. if (interfaceInfo.extendsClause) {
  160. output += interfaceInfo.extendsClause.getText() + ' ';
  161. }
  162. output += '{\n';
  163. output += members.map(member => `${INDENT}${member.fullText}`).join('\n');
  164. output += '\n}\n';
  165. output += '```\n';
  166. return output;
  167. }
  168. private renderClassSignature(classInfo: ClassInfo): string {
  169. const { fullText, members } = classInfo;
  170. let output = '';
  171. output += '```ts title="Signature"\n';
  172. output += `class ${fullText} `;
  173. if (classInfo.extendsClause) {
  174. output += classInfo.extendsClause.getText() + ' ';
  175. }
  176. if (classInfo.implementsClause) {
  177. output += classInfo.implementsClause.getText() + ' ';
  178. }
  179. output += '{\n';
  180. const renderModifiers = (modifiers: string[]) => (modifiers.length ? modifiers.join(' ') + ' ' : '');
  181. output += members
  182. .map(member => {
  183. if (member.kind === 'method') {
  184. const args = member.parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  185. if (member.fullText === 'constructor') {
  186. return `${INDENT}constructor(${args})`;
  187. } else {
  188. return `${INDENT}${member.fullText}(${args}) => ${member.type};`;
  189. }
  190. } else {
  191. return `${INDENT}${member.fullText}`;
  192. }
  193. })
  194. .join('\n');
  195. output += '\n}\n';
  196. output += '```\n';
  197. return output;
  198. }
  199. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  200. const { fullText, members, type } = typeAliasInfo;
  201. let output = '';
  202. output += '```ts title="Signature"\n';
  203. output += `type ${fullText} = `;
  204. if (members) {
  205. output += '{\n';
  206. output += members.map(member => `${INDENT}${member.fullText}`).join('\n');
  207. output += '\n}\n';
  208. } else {
  209. output += type.getText() + '\n';
  210. }
  211. output += '```\n';
  212. return output;
  213. }
  214. private renderEnumSignature(enumInfo: EnumInfo): string {
  215. const { fullText, members } = enumInfo;
  216. let output = '';
  217. output += '```ts title="Signature"\n';
  218. output += `enum ${fullText} `;
  219. if (members) {
  220. output += '{\n';
  221. output += members
  222. .map(member => {
  223. let line = member.description ? `${INDENT}// ${member.description}\n` : '';
  224. line += `${INDENT}${member.fullText}`;
  225. return line;
  226. })
  227. .join('\n');
  228. output += '\n}\n';
  229. }
  230. output += '```\n';
  231. return output;
  232. }
  233. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  234. const { fullText, parameters, type } = functionInfo;
  235. const args = parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  236. let output = '';
  237. output += '```ts title="Signature"\n';
  238. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  239. output += '```\n';
  240. return output;
  241. }
  242. private renderFunctionParams(
  243. params: MethodParameterInfo[],
  244. knownTypeMap: TypeMap,
  245. docsUrl: string,
  246. ): string {
  247. let output = '';
  248. for (const param of params) {
  249. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  250. output += `### ${param.name}\n\n`;
  251. output += `<MemberInfo kind="parameter" type={\`${type}\`} />\n\n`;
  252. }
  253. return output;
  254. }
  255. private renderMembers(
  256. info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo,
  257. knownTypeMap: TypeMap,
  258. docsUrl: string,
  259. ): string {
  260. const { members, title } = info;
  261. let output = '';
  262. for (const member of members || []) {
  263. let defaultParam = '';
  264. let sinceParam = '';
  265. let experimentalParam = '';
  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. if (member.experimental) {
  286. experimentalParam = 'experimental="true"';
  287. }
  288. output += `\n### ${member.name}\n\n`;
  289. output += `<MemberInfo kind="${[member.kind].join(
  290. ' ',
  291. )}" type={\`${type}\`} ${defaultParam} ${sinceParam}${experimentalParam} />\n\n`;
  292. output += this.renderDescription(member.description, knownTypeMap, docsUrl);
  293. }
  294. return output;
  295. }
  296. private renderHeritageClause(clause: HeritageClause, knownTypeMap: TypeMap, docsUrl: string) {
  297. return (
  298. clause.types
  299. .map(t => `<code>${this.renderType(t.getText(), knownTypeMap, docsUrl)}</code>`)
  300. .join(', ') + '\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. let experimental = '';
  315. if (info.experimental) {
  316. experimental = ' experimental="true"';
  317. }
  318. return `<GenerationInfo sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}"${sinceData}${experimental} />\n\n`;
  319. }
  320. /**
  321. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  322. * and known types (e.g. "ShippingMethod") into hyperlinks.
  323. */
  324. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  325. let typeText = type
  326. .trim()
  327. // encode HTML entities
  328. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  329. // remove newlines
  330. .replace(/\n/g, ' ');
  331. for (const [key, val] of knownTypeMap) {
  332. const re = new RegExp(`\\b${key}\\b`, 'g');
  333. const strippedIndex = val.replace(/\/_index$/, '');
  334. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}'>${key}</a>`);
  335. }
  336. return typeText;
  337. }
  338. /**
  339. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  340. */
  341. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  342. for (const [key, val] of knownTypeMap) {
  343. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  344. description = description.replace(re, `<a href='${docsUrl}/${val}'>${key}</a>`);
  345. }
  346. return description;
  347. }
  348. }