typescript-docs-renderer.ts 15 KB

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