generate-docs.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. }
  16. interface PropertyInfo extends MemberInfo {
  17. kind: 'property';
  18. defaultValue: string;
  19. }
  20. interface MethodInfo extends MemberInfo {
  21. kind: 'method';
  22. parameters: MethodParameterInfo[];
  23. }
  24. interface DeclarationInfo {
  25. sourceFile: string;
  26. sourceLine: number;
  27. title: string;
  28. weight: number;
  29. category: string;
  30. description: string;
  31. fileName: string;
  32. }
  33. interface InterfaceInfo extends DeclarationInfo {
  34. kind: 'interface';
  35. members: Array<PropertyInfo | MethodInfo>;
  36. }
  37. interface TypeAliasInfo extends DeclarationInfo {
  38. kind: 'typeAlias';
  39. type: string;
  40. }
  41. type ValidDeclaration = ts.InterfaceDeclaration | ts.TypeAliasDeclaration;
  42. type TypeMap = Map<string, string>;
  43. const docsPath = '/docs/api/';
  44. const outputPath = path.join(__dirname, '../docs/content/docs/api');
  45. /**
  46. * This map is used to cache types and their corresponding Hugo path. It is used to enable
  47. * hyperlinking from a member's "type" to the definition of that type.
  48. */
  49. const globalTypeMap: TypeMap = new Map();
  50. const tsFiles = klawSync(path.join(__dirname, '../server/src/'), {
  51. nodir: true,
  52. filter: item => path.extname(item.path) === '.ts',
  53. traverseAll: true,
  54. }).map(item => item.path);
  55. deleteGeneratedDocs();
  56. generateDocs(tsFiles, outputPath, globalTypeMap);
  57. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  58. if (watchMode) {
  59. console.log(`Watching for changes to source files...`);
  60. tsFiles.forEach(file => {
  61. fs.watchFile(file, { interval: 1000 }, () => {
  62. generateDocs([file], outputPath, globalTypeMap);
  63. });
  64. });
  65. }
  66. /**
  67. * Delete all generated docs found in the outputPath.
  68. */
  69. function deleteGeneratedDocs() {
  70. let deleteCount = 0;
  71. const files = klawSync(outputPath, { nodir: true });
  72. for (const file of files) {
  73. const content = fs.readFileSync(file.path, 'utf-8');
  74. if (isGenerated(content)) {
  75. fs.unlinkSync(file.path);
  76. deleteCount++;
  77. }
  78. }
  79. console.log(`Deleted ${deleteCount} generated docs`);
  80. }
  81. /**
  82. * Returns true if the content matches that of a generated document.
  83. */
  84. function isGenerated(content: string) {
  85. return /generated\: true\n---\n/.test(content);
  86. }
  87. /**
  88. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  89. * into markdown files
  90. * @param filePaths
  91. * @param typeMap
  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.text;
  168. const weight = getDeclarationWeight(statement);
  169. const description = getDeclarationDescription(statement);
  170. const fileName = title
  171. .split(/(?=[A-Z])/)
  172. .join('-')
  173. .toLowerCase();
  174. const info = {
  175. sourceFile,
  176. sourceLine,
  177. title,
  178. weight,
  179. category,
  180. description,
  181. fileName,
  182. };
  183. if (ts.isInterfaceDeclaration(statement)) {
  184. return {
  185. ...info,
  186. kind: 'interface',
  187. members: parseMembers(statement.members),
  188. };
  189. } else if (ts.isTypeAliasDeclaration(statement)) {
  190. return {
  191. ...info,
  192. type: statement.type.getFullText().trim(),
  193. kind: 'typeAlias',
  194. };
  195. }
  196. }
  197. /**
  198. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  199. */
  200. function parseMembers(members: ts.NodeArray<ts.TypeElement>): Array<PropertyInfo | MethodInfo> {
  201. const result: Array<PropertyInfo | MethodInfo> = [];
  202. for (const member of members) {
  203. if (ts.isPropertySignature(member) || ts.isMethodSignature(member)) {
  204. const name = member.name.getText();
  205. let description = '';
  206. let type = '';
  207. let defaultValue = '';
  208. let parameters: MethodParameterInfo[] = [];
  209. parseTags(member, {
  210. description: tag => (description += tag.comment || ''),
  211. example: tag => (description += formatExampleCode(tag.comment)),
  212. default: tag => (defaultValue = tag.comment || ''),
  213. });
  214. if (member.type) {
  215. type = member.type.getFullText().trim();
  216. }
  217. if (ts.isMethodSignature(member)) {
  218. parameters = member.parameters.map(p => ({
  219. name: p.name.getText(),
  220. type: p.type ? p.type.getFullText() : '',
  221. }));
  222. result.push({
  223. kind: 'method',
  224. name,
  225. description,
  226. type,
  227. parameters,
  228. });
  229. } else {
  230. result.push({
  231. kind: 'property',
  232. name,
  233. description,
  234. type,
  235. defaultValue,
  236. });
  237. }
  238. }
  239. }
  240. return result;
  241. }
  242. /**
  243. * Render the interface to a markdown string.
  244. */
  245. function renderInterface(interfaceInfo: InterfaceInfo, knownTypeMap: Map<string, string>): string {
  246. const { title, weight, category, description, sourceFile, members } = interfaceInfo;
  247. let output = '';
  248. output += generateFrontMatter(title, weight);
  249. output += `\n\n# ${title}\n\n`;
  250. output += renderGenerationInfoShortcode(interfaceInfo);
  251. output += `${description}\n\n`;
  252. output += `## Signature\n\n`;
  253. output += renderInterfaceSignature(interfaceInfo);
  254. output += `## Members\n\n`;
  255. for (const member of members) {
  256. let defaultParam = '';
  257. let type = '';
  258. if (member.kind === 'property') {
  259. type = renderType(member.type, knownTypeMap);
  260. defaultParam = member.defaultValue ? `default="${member.defaultValue}" ` : '';
  261. } else {
  262. const args = member.parameters
  263. .map(p => {
  264. return `${p.name}: ${renderType(p.type, knownTypeMap)}`;
  265. })
  266. .join(', ');
  267. type = `(${args}) => ${renderType(member.type, knownTypeMap)}`;
  268. }
  269. output += `### ${member.name}\n\n`;
  270. output += `{{< member-info kind="${member.kind}" type="${type}" ${defaultParam}>}}\n\n`;
  271. output += `${member.description}\n\n`;
  272. }
  273. return output;
  274. }
  275. /**
  276. * Generates a markdown code block string for the interface signature.
  277. */
  278. function renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  279. const { title, members } = interfaceInfo;
  280. let output = '';
  281. output += `\`\`\`ts\n`;
  282. output += `interface ${title} {\n`;
  283. output += members.map(member => {
  284. if (member.kind === 'property') {
  285. return ` ${member.name}: ${member.type};`;
  286. } else {
  287. const args = member.parameters
  288. .map(p => `${p.name}: ${p.type}`)
  289. .join(', ');
  290. return ` ${member.name}: (${args}) => ${member.type}`;
  291. }
  292. }).join(`\n`) ;
  293. output += `\n}\n`;
  294. output += `\`\`\`\n`;
  295. return output;
  296. }
  297. /**
  298. * Render the type alias to a markdown string.
  299. */
  300. function renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: Map<string, string>): string {
  301. const { title, weight, category, description, sourceFile, sourceLine, type } = typeAliasInfo;
  302. let output = '';
  303. output += generateFrontMatter(title, weight);
  304. output += `\n\n# ${title}\n\n`;
  305. output += renderGenerationInfoShortcode(typeAliasInfo);
  306. output += `${description}\n\n`;
  307. output += `## Signature\n\n`;
  308. output += `\`\`\`ts\ntype ${title} = ${type};\n\`\`\``;
  309. return output;
  310. }
  311. function renderGenerationInfoShortcode(info: DeclarationInfo): string {
  312. return `{{< generation-info sourceFile="${info.sourceFile}" sourceLine="${info.sourceLine}">}}\n\n`;
  313. }
  314. /**
  315. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  316. */
  317. function getDocsCategory(statement: ValidDeclaration): string | undefined {
  318. let category: string | undefined;
  319. parseTags(statement, {
  320. docsCategory: tag => (category = tag.comment || ''),
  321. });
  322. return category;
  323. }
  324. /**
  325. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  326. */
  327. function parseTags<T extends ts.Node>(
  328. node: T,
  329. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  330. ): void {
  331. const jsDocTags = ts.getJSDocTags(node);
  332. for (const tag of jsDocTags) {
  333. const tagName = tag.tagName.text;
  334. if (tagMatcher[tagName]) {
  335. tagMatcher[tagName](tag);
  336. }
  337. }
  338. }
  339. /**
  340. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  341. * and known types (e.g. "ShippingMethod") into hyperlinks.
  342. */
  343. function renderType(type: string, knownTypeMap: Map<string, string>): string {
  344. let typeText = type
  345. .trim()
  346. // encode HTML entities
  347. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  348. // remove newlines
  349. .replace(/\n/g, ' ');
  350. for (const [key, val] of knownTypeMap) {
  351. typeText = typeText.replace(key, `<a href='${docsPath}/${val}/'>${key}</a>`);
  352. }
  353. return typeText;
  354. }
  355. /**
  356. * Generates the Hugo front matter with the title of the document
  357. */
  358. function generateFrontMatter(title: string, weight: number, showToc: boolean = true): string {
  359. return `---
  360. title: "${title}"
  361. weight: ${weight}
  362. date: ${new Date().toISOString()}
  363. showtoc: ${showToc}
  364. generated: true
  365. ---
  366. <!-- This file was generated from the Vendure TypeScript source. Do not modify. Instead, re-run "generate-docs" -->
  367. `;
  368. }
  369. /**
  370. * Reads the @docsWeight JSDoc tag from the interface.
  371. */
  372. function getDeclarationWeight(statement: ValidDeclaration): number {
  373. let weight = 10;
  374. parseTags(statement, {
  375. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  376. });
  377. return weight;
  378. }
  379. /**
  380. * Reads the @description JSDoc tag from the interface.
  381. */
  382. function getDeclarationDescription(statement: ValidDeclaration): string {
  383. let description = '';
  384. parseTags(statement, {
  385. description: tag => (description += tag.comment),
  386. });
  387. return description;
  388. }
  389. /**
  390. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  391. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  392. */
  393. function formatExampleCode(example: string = ''): string {
  394. return '\n\n' + example.replace(/\n\s+\*\s/g, '');
  395. }
  396. /**
  397. * Type guard for the types of statement which can ge processed by the doc generator.
  398. */
  399. function isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  400. return ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement);
  401. }