generate-config-docs.ts 17 KB

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