typescript-docs-renderer.ts 15 KB

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