generate-docs.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. import fs from 'fs';
  2. import klawSync from 'klaw-sync';
  3. import path from 'path';
  4. import ts from 'typescript';
  5. import { notNullOrUndefined } from '../shared/shared-utils';
  6. // tslint:disable:no-console
  7. interface MethodParameterInfo {
  8. name: string;
  9. type: string;
  10. }
  11. interface MemberInfo {
  12. name: string;
  13. description: string;
  14. type: string;
  15. fullText: string;
  16. }
  17. interface PropertyInfo extends MemberInfo {
  18. kind: 'property';
  19. defaultValue: string;
  20. }
  21. interface MethodInfo extends MemberInfo {
  22. kind: 'method';
  23. parameters: MethodParameterInfo[];
  24. }
  25. interface DeclarationInfo {
  26. sourceFile: string;
  27. sourceLine: number;
  28. title: string;
  29. fullText: string;
  30. weight: number;
  31. category: string;
  32. description: string;
  33. fileName: string;
  34. }
  35. interface InterfaceInfo extends DeclarationInfo {
  36. kind: 'interface';
  37. members: Array<PropertyInfo | MethodInfo>;
  38. }
  39. interface TypeAliasInfo extends DeclarationInfo {
  40. kind: 'typeAlias';
  41. type: string;
  42. }
  43. type ValidDeclaration = ts.InterfaceDeclaration | ts.TypeAliasDeclaration;
  44. type TypeMap = Map<string, string>;
  45. const docsPath = '/docs/api/';
  46. const outputPath = path.join(__dirname, '../docs/content/docs/api');
  47. /**
  48. * This map is used to cache types and their corresponding Hugo path. It is used to enable
  49. * hyperlinking from a member's "type" to the definition of that type.
  50. */
  51. const globalTypeMap: TypeMap = new Map();
  52. const tsFiles = klawSync(path.join(__dirname, '../server/src/'), {
  53. nodir: true,
  54. filter: item => path.extname(item.path) === '.ts',
  55. traverseAll: true,
  56. }).map(item => item.path);
  57. deleteGeneratedDocs();
  58. generateDocs(tsFiles, outputPath, globalTypeMap);
  59. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  60. if (watchMode) {
  61. console.log(`Watching for changes to source files...`);
  62. tsFiles.forEach(file => {
  63. fs.watchFile(file, { interval: 1000 }, () => {
  64. generateDocs([file], outputPath, globalTypeMap);
  65. });
  66. });
  67. }
  68. /**
  69. * Delete all generated docs found in the outputPath.
  70. */
  71. function deleteGeneratedDocs() {
  72. let deleteCount = 0;
  73. const files = klawSync(outputPath, { nodir: true });
  74. for (const file of files) {
  75. const content = fs.readFileSync(file.path, 'utf-8');
  76. if (isGenerated(content)) {
  77. fs.unlinkSync(file.path);
  78. deleteCount++;
  79. }
  80. }
  81. console.log(`Deleted ${deleteCount} generated docs`);
  82. }
  83. /**
  84. * Returns true if the content matches that of a generated document.
  85. */
  86. function isGenerated(content: string) {
  87. return /generated\: true\n---\n/.test(content);
  88. }
  89. /**
  90. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  91. * into markdown files
  92. */
  93. function generateDocs(filePaths: string[], hugoApiDocsPath: string, typeMap: TypeMap) {
  94. const timeStart = +new Date();
  95. const sourceFiles = filePaths.map(filePath => {
  96. return ts.createSourceFile(
  97. filePath,
  98. fs.readFileSync(filePath).toString(),
  99. ts.ScriptTarget.ES2015,
  100. true,
  101. );
  102. });
  103. const statements = getStatementsWithSourceLocation(sourceFiles);
  104. const declarationInfos = statements
  105. .map(statement => {
  106. const info = parseDeclaration(statement.statement, statement.sourceFile, statement.sourceLine);
  107. if (info) {
  108. typeMap.set(info.title, info.category + '/' + info.fileName);
  109. }
  110. return info;
  111. })
  112. .filter(notNullOrUndefined);
  113. for (const info of declarationInfos) {
  114. let markdown = '';
  115. switch (info.kind) {
  116. case 'interface':
  117. markdown = renderInterface(info, typeMap);
  118. break;
  119. case 'typeAlias':
  120. markdown = renderTypeAlias(info, typeMap);
  121. break;
  122. }
  123. const categoryDir = path.join(hugoApiDocsPath, info.category);
  124. const indexFile = path.join(categoryDir, '_index.md');
  125. if (!fs.existsSync(categoryDir)) {
  126. fs.mkdirSync(categoryDir);
  127. }
  128. if (!fs.existsSync(indexFile)) {
  129. const indexFileContent = generateFrontMatter(info.category, 10, false) + `\n\n# ${info.category}`;
  130. fs.writeFileSync(indexFile, indexFileContent);
  131. }
  132. fs.writeFileSync(path.join(categoryDir, info.fileName + '.md'), markdown);
  133. }
  134. if (declarationInfos.length) {
  135. console.log(`Generated ${declarationInfos.length} docs in ${+new Date() - timeStart}ms`);
  136. }
  137. }
  138. /**
  139. * Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
  140. * came from.
  141. */
  142. function getStatementsWithSourceLocation(sourceFiles: ts.SourceFile[]): Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number; }> {
  143. return sourceFiles.reduce(
  144. (st, sf) => {
  145. const statementsWithSources = sf.statements.map(statement => {
  146. const serverSourceRoot = '/server/src';
  147. const sourceFile = sf.fileName.substring(sf.fileName.indexOf(serverSourceRoot));
  148. const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
  149. return {statement, sourceFile, sourceLine };
  150. });
  151. return [...st, ...statementsWithSources];
  152. },
  153. [] as Array<{ statement: ts.Statement; sourceFile: string, sourceLine: number; }>,
  154. );
  155. }
  156. /**
  157. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  158. */
  159. function parseDeclaration(statement: ts.Statement, sourceFile: string, sourceLine: number): InterfaceInfo | TypeAliasInfo | undefined {
  160. if (!isValidDeclaration(statement)) {
  161. return;
  162. }
  163. const category = getDocsCategory(statement);
  164. if (category === undefined) {
  165. return;
  166. }
  167. const title = statement.name.getText();
  168. const fullText = getDeclarationFullText(statement);
  169. const weight = getDeclarationWeight(statement);
  170. const description = getDeclarationDescription(statement);
  171. const fileName = title
  172. .split(/(?=[A-Z])/)
  173. .join('-')
  174. .toLowerCase();
  175. const info = {
  176. sourceFile,
  177. sourceLine,
  178. fullText,
  179. title,
  180. weight,
  181. category,
  182. description,
  183. fileName,
  184. };
  185. if (ts.isInterfaceDeclaration(statement)) {
  186. return {
  187. ...info,
  188. kind: 'interface',
  189. members: parseMembers(statement.members),
  190. };
  191. } else if (ts.isTypeAliasDeclaration(statement)) {
  192. return {
  193. ...info,
  194. type: statement.type.getFullText().trim(),
  195. kind: 'typeAlias',
  196. };
  197. }
  198. }
  199. /**
  200. * Returns the declaration name plus any type parameters.
  201. */
  202. function getDeclarationFullText(declaration: ValidDeclaration): string {
  203. const name = declaration.name.getText();
  204. let typeParams = '';
  205. if (declaration.typeParameters) {
  206. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  207. }
  208. return name + typeParams;
  209. }
  210. /**
  211. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  212. */
  213. function parseMembers(members: ts.NodeArray<ts.TypeElement>): Array<PropertyInfo | MethodInfo> {
  214. const result: Array<PropertyInfo | MethodInfo> = [];
  215. for (const member of members) {
  216. if (ts.isPropertySignature(member) || ts.isMethodSignature(member)) {
  217. const name = member.name.getText();
  218. let description = '';
  219. let type = '';
  220. let defaultValue = '';
  221. let parameters: MethodParameterInfo[] = [];
  222. const fullText = member.getText();
  223. parseTags(member, {
  224. description: tag => (description += tag.comment || ''),
  225. example: tag => (description += formatExampleCode(tag.comment)),
  226. default: tag => (defaultValue = tag.comment || ''),
  227. });
  228. if (member.type) {
  229. type = member.type.getFullText().trim();
  230. }
  231. const memberInfo: MemberInfo = {
  232. fullText,
  233. name,
  234. description,
  235. type,
  236. };
  237. if (ts.isMethodSignature(member)) {
  238. parameters = member.parameters.map(p => ({
  239. name: p.name.getText(),
  240. type: p.type ? p.type.getFullText() : '',
  241. }));
  242. result.push({
  243. ...memberInfo,
  244. kind: 'method',
  245. parameters,
  246. });
  247. } else {
  248. result.push({
  249. ...memberInfo,
  250. kind: 'property',
  251. defaultValue,
  252. });
  253. }
  254. }
  255. }
  256. return result;
  257. }
  258. /**
  259. * Render the interface to a markdown string.
  260. */
  261. function renderInterface(interfaceInfo: InterfaceInfo, knownTypeMap: Map<string, string>): string {
  262. const { title, weight, category, description, members } = interfaceInfo;
  263. let output = '';
  264. output += generateFrontMatter(title, weight);
  265. output += `\n\n# ${title}\n\n`;
  266. output += renderGenerationInfoShortcode(interfaceInfo);
  267. output += `${description}\n\n`;
  268. output += `## Signature\n\n`;
  269. output += renderInterfaceSignature(interfaceInfo);
  270. output += `## Members\n\n`;
  271. for (const member of members) {
  272. let defaultParam = '';
  273. let type = '';
  274. if (member.kind === 'property') {
  275. type = renderType(member.type, knownTypeMap);
  276. defaultParam = member.defaultValue ? `default="${member.defaultValue}" ` : '';
  277. } else {
  278. const args = member.parameters
  279. .map(p => {
  280. return `${p.name}: ${renderType(p.type, knownTypeMap)}`;
  281. })
  282. .join(', ');
  283. type = `(${args}) => ${renderType(member.type, knownTypeMap)}`;
  284. }
  285. output += `### ${member.name}\n\n`;
  286. output += `{{< member-info kind="${member.kind}" type="${type}" ${defaultParam}>}}\n\n`;
  287. output += `${member.description}\n\n`;
  288. }
  289. return output;
  290. }
  291. /**
  292. * Generates a markdown code block string for the interface signature.
  293. */
  294. function renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  295. const { fullText, members } = interfaceInfo;
  296. let output = '';
  297. output += `\`\`\`ts\n`;
  298. output += `interface ${fullText} {\n`;
  299. output += members.map(member => ` ${member.fullText}`).join(`\n`) ;
  300. output += `\n}\n`;
  301. output += `\`\`\`\n`;
  302. return output;
  303. }
  304. /**
  305. * Render the type alias to a markdown string.
  306. */
  307. function renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: Map<string, string>): string {
  308. const { title, weight, description, type, fullText } = typeAliasInfo;
  309. let output = '';
  310. output += generateFrontMatter(title, weight);
  311. output += `\n\n# ${title}\n\n`;
  312. output += renderGenerationInfoShortcode(typeAliasInfo);
  313. output += `${description}\n\n`;
  314. output += `## Signature\n\n`;
  315. output += `\`\`\`ts\ntype ${fullText} = ${type};\n\`\`\``;
  316. return output;
  317. }
  318. function renderGenerationInfoShortcode(info: DeclarationInfo): string {
  319. return `{{< generation-info sourceFile="${info.sourceFile}" sourceLine="${info.sourceLine}">}}\n\n`;
  320. }
  321. /**
  322. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  323. */
  324. function getDocsCategory(statement: ValidDeclaration): string | undefined {
  325. let category: string | undefined;
  326. parseTags(statement, {
  327. docsCategory: tag => (category = tag.comment || ''),
  328. });
  329. return category;
  330. }
  331. /**
  332. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  333. */
  334. function parseTags<T extends ts.Node>(
  335. node: T,
  336. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  337. ): void {
  338. const jsDocTags = ts.getJSDocTags(node);
  339. for (const tag of jsDocTags) {
  340. const tagName = tag.tagName.text;
  341. if (tagMatcher[tagName]) {
  342. tagMatcher[tagName](tag);
  343. }
  344. }
  345. }
  346. /**
  347. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  348. * and known types (e.g. "ShippingMethod") into hyperlinks.
  349. */
  350. function renderType(type: string, knownTypeMap: Map<string, string>): string {
  351. let typeText = type
  352. .trim()
  353. // encode HTML entities
  354. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  355. // remove newlines
  356. .replace(/\n/g, ' ');
  357. for (const [key, val] of knownTypeMap) {
  358. typeText = typeText.replace(key, `<a href='${docsPath}/${val}/'>${key}</a>`);
  359. }
  360. return typeText;
  361. }
  362. /**
  363. * Generates the Hugo front matter with the title of the document
  364. */
  365. function generateFrontMatter(title: string, weight: number, showToc: boolean = true): string {
  366. return `---
  367. title: "${title}"
  368. weight: ${weight}
  369. date: ${new Date().toISOString()}
  370. showtoc: ${showToc}
  371. generated: true
  372. ---
  373. <!-- This file was generated from the Vendure TypeScript source. Do not modify. Instead, re-run "generate-docs" -->
  374. `;
  375. }
  376. /**
  377. * Reads the @docsWeight JSDoc tag from the interface.
  378. */
  379. function getDeclarationWeight(statement: ValidDeclaration): number {
  380. let weight = 10;
  381. parseTags(statement, {
  382. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  383. });
  384. return weight;
  385. }
  386. /**
  387. * Reads the @description JSDoc tag from the interface.
  388. */
  389. function getDeclarationDescription(statement: ValidDeclaration): string {
  390. let description = '';
  391. parseTags(statement, {
  392. description: tag => (description += tag.comment),
  393. });
  394. return description;
  395. }
  396. /**
  397. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  398. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  399. */
  400. function formatExampleCode(example: string = ''): string {
  401. return '\n\n' + example.replace(/\n\s+\*\s/g, '');
  402. }
  403. /**
  404. * Type guard for the types of statement which can ge processed by the doc generator.
  405. */
  406. function isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  407. return ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement);
  408. }