typescript-docs-renderer.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. 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.mkdirSync(outputPath);
  24. }
  25. for (const page of pages) {
  26. let markdown = '';
  27. markdown += generateFrontMatter(page.title, 10);
  28. const declarationsByWeight = page.declarations.sort((a, b) => a.weight - b.weight);
  29. for (const info of declarationsByWeight) {
  30. switch (info.kind) {
  31. case 'interface':
  32. markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
  33. break;
  34. case 'typeAlias':
  35. markdown += this.renderTypeAlias(info, typeMap, docsUrl);
  36. break;
  37. case 'class':
  38. markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
  39. break;
  40. case 'enum':
  41. markdown += this.renderEnum(info, typeMap, docsUrl);
  42. break;
  43. case 'function':
  44. markdown += this.renderFunction(info, typeMap, docsUrl);
  45. break;
  46. case 'variable':
  47. markdown += this.renderVariable(info, typeMap, docsUrl);
  48. break;
  49. default:
  50. assertNever(info);
  51. }
  52. }
  53. const categoryDir = path.join(outputPath, ...page.category);
  54. if (!fs.existsSync(categoryDir)) {
  55. fs.mkdirsSync(categoryDir);
  56. }
  57. const pathParts = [];
  58. for (const subCategory of page.category) {
  59. pathParts.push(subCategory);
  60. const indexFile = path.join(outputPath, ...pathParts, '_index.md');
  61. if (!fs.existsSync(indexFile)) {
  62. const indexFileContent =
  63. generateFrontMatter(subCategory, 10, false) + `\n\n# ${subCategory}`;
  64. fs.writeFileSync(indexFile, indexFileContent);
  65. generatedCount++;
  66. }
  67. }
  68. fs.writeFileSync(path.join(categoryDir, page.fileName + '.md'), markdown);
  69. generatedCount++;
  70. }
  71. return generatedCount;
  72. }
  73. /**
  74. * Render the interface to a markdown string.
  75. */
  76. private renderInterfaceOrClass(
  77. info: InterfaceInfo | ClassInfo,
  78. knownTypeMap: TypeMap,
  79. docsUrl: string,
  80. ): string {
  81. const { title, weight, category, description, members } = info;
  82. let output = '';
  83. output += `\n\n## ${title}\n\n`;
  84. output += this.renderGenerationInfoShortcode(info);
  85. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  86. output +=
  87. info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  88. if (info.extendsClause) {
  89. output += 'Extends\n\n';
  90. output += `${this.renderHeritageClause(info.extendsClause, knownTypeMap, docsUrl)}\n`;
  91. }
  92. if (info.kind === 'class' && info.implementsClause) {
  93. output += 'Implements\n\n';
  94. output += `${this.renderHeritageClause(info.implementsClause, knownTypeMap, docsUrl)}\n`;
  95. }
  96. if (info.members && info.members.length) {
  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 += this.renderTypeAliasSignature(typeAliasInfo);
  111. if (typeAliasInfo.members && typeAliasInfo.members.length) {
  112. output += '## Members\n\n';
  113. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  114. }
  115. return output;
  116. }
  117. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  118. const { title, weight, description, fullText } = enumInfo;
  119. let output = '';
  120. output += `\n\n## ${title}\n\n`;
  121. output += this.renderGenerationInfoShortcode(enumInfo);
  122. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  123. output += this.renderEnumSignature(enumInfo);
  124. return output;
  125. }
  126. private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  127. const { title, weight, description, fullText, parameters } = functionInfo;
  128. let output = '';
  129. output += `\n\n## ${title}\n\n`;
  130. output += this.renderGenerationInfoShortcode(functionInfo);
  131. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  132. output += this.renderFunctionSignature(functionInfo, knownTypeMap);
  133. if (parameters.length) {
  134. output += 'Parameters\n\n';
  135. output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
  136. }
  137. return output;
  138. }
  139. private renderVariable(variableInfo: VariableInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  140. const { title, weight, description, fullText } = variableInfo;
  141. let output = '';
  142. output += `\n\n## ${title}\n\n`;
  143. output += this.renderGenerationInfoShortcode(variableInfo);
  144. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  145. return output;
  146. }
  147. /**
  148. * Generates a markdown code block string for the interface signature.
  149. */
  150. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  151. const { fullText, members } = interfaceInfo;
  152. let output = '';
  153. output += '```ts title="Signature"\n';
  154. output += `interface ${fullText} `;
  155. if (interfaceInfo.extendsClause) {
  156. output += interfaceInfo.extendsClause.getText() + ' ';
  157. }
  158. output += '{\n';
  159. output += members.map(member => ` ${member.fullText}`).join('\n');
  160. output += '\n}\n';
  161. output += '```\n';
  162. return output;
  163. }
  164. private renderClassSignature(classInfo: ClassInfo): string {
  165. const { fullText, members } = classInfo;
  166. let output = '';
  167. output += '```ts title="Signature"\n';
  168. output += `class ${fullText} `;
  169. if (classInfo.extendsClause) {
  170. output += classInfo.extendsClause.getText() + ' ';
  171. }
  172. if (classInfo.implementsClause) {
  173. output += classInfo.implementsClause.getText() + ' ';
  174. }
  175. output += '{\n';
  176. const renderModifiers = (modifiers: string[]) => (modifiers.length ? modifiers.join(' ') + ' ' : '');
  177. output += members
  178. .map(member => {
  179. if (member.kind === 'method') {
  180. const args = member.parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  181. if (member.fullText === 'constructor') {
  182. return ` constructor(${args})`;
  183. } else {
  184. return ` ${renderModifiers(member.modifiers)}${member.fullText}(${args}) => ${
  185. member.type
  186. };`;
  187. }
  188. } else {
  189. return ` ${renderModifiers(member.modifiers)}${member.fullText}`;
  190. }
  191. })
  192. .join('\n');
  193. output += '\n}\n';
  194. output += '```\n';
  195. return output;
  196. }
  197. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  198. const { fullText, members, type } = typeAliasInfo;
  199. let output = '';
  200. output += '```ts title="Signature"\n';
  201. output += `type ${fullText} = `;
  202. if (members) {
  203. output += '{\n';
  204. output += members.map(member => ` ${member.fullText}`).join('\n');
  205. output += '\n}\n';
  206. } else {
  207. output += type.getText() + '\n';
  208. }
  209. output += '```\n';
  210. return output;
  211. }
  212. private renderEnumSignature(enumInfo: EnumInfo): string {
  213. const { fullText, members } = enumInfo;
  214. let output = '';
  215. output += '```ts title="Signature"\n';
  216. output += `enum ${fullText} `;
  217. if (members) {
  218. output += '{\n';
  219. output += members
  220. .map(member => {
  221. let line = member.description ? ` // ${member.description}\n` : '';
  222. line += ` ${member.fullText}`;
  223. return line;
  224. })
  225. .join('\n');
  226. output += '\n}\n';
  227. }
  228. output += '```\n';
  229. return output;
  230. }
  231. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  232. const { fullText, parameters, type } = functionInfo;
  233. const args = parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  234. let output = '';
  235. output += '```ts title="Signature"\n';
  236. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  237. output += '```\n';
  238. return output;
  239. }
  240. private renderFunctionParams(
  241. params: MethodParameterInfo[],
  242. knownTypeMap: TypeMap,
  243. docsUrl: string,
  244. ): string {
  245. let output = '';
  246. for (const param of params) {
  247. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  248. output += `### ${param.name}\n\n`;
  249. output += `<MemberInfo kind="parameter" type="${type}" />\n\n`;
  250. }
  251. return output;
  252. }
  253. private renderMembers(
  254. info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo,
  255. knownTypeMap: TypeMap,
  256. docsUrl: string,
  257. ): string {
  258. const { members, title } = info;
  259. let output = '';
  260. for (const member of members || []) {
  261. let defaultParam = '';
  262. let sinceParam = '';
  263. let experimentalParam = '';
  264. let type = '';
  265. if (member.kind === 'property') {
  266. type = this.renderType(member.type, knownTypeMap, docsUrl);
  267. defaultParam = member.defaultValue
  268. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  269. : '';
  270. } else {
  271. const args = member.parameters
  272. .map(p => this.renderParameter(p, this.renderType(p.type, knownTypeMap, docsUrl)))
  273. .join(', ');
  274. if (member.fullText === 'constructor') {
  275. type = `(${args}) => ${title}`;
  276. } else {
  277. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  278. }
  279. }
  280. if (member.since) {
  281. sinceParam = `since="${member.since}" `;
  282. }
  283. if (member.experimental) {
  284. experimentalParam = 'experimental="true"';
  285. }
  286. output += `\n### ${member.name}\n\n`;
  287. output += `<MemberInfo kind="${[member.kind].join(
  288. ' ',
  289. )}" type="${type}" ${defaultParam} ${sinceParam}${experimentalParam} />\n\n`;
  290. // output += `<MemberDescription description={\`${this.renderDescription(
  291. // member.description,
  292. // knownTypeMap,
  293. // docsUrl,
  294. // )}\`} />\n\n`;
  295. output += this.renderDescription(member.description, knownTypeMap, docsUrl);
  296. }
  297. return output;
  298. }
  299. private renderHeritageClause(clause: HeritageClause, knownTypeMap: TypeMap, docsUrl: string) {
  300. return (
  301. clause.types.map(t => ` * ${this.renderType(t.getText(), knownTypeMap, docsUrl)}`).join('\n') +
  302. '\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(`\\b${key}\\b`, '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. }