generate-typescript-docs.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /* tslint:disable:no-console */
  2. import fs from 'fs-extra';
  3. import klawSync from 'klaw-sync';
  4. import path, { extname } from 'path';
  5. import { deleteGeneratedDocs } from './docgen-utils';
  6. import { TypeMap } from './typescript-docgen-types';
  7. import { TypescriptDocsParser } from './typescript-docs-parser';
  8. import { TypescriptDocsRenderer } from './typescript-docs-renderer';
  9. interface DocsSectionConfig {
  10. sourceDirs: string[];
  11. exclude?: RegExp[];
  12. outputPath: string;
  13. }
  14. const sections: DocsSectionConfig[] = [
  15. {
  16. sourceDirs: [
  17. 'packages/core/src/',
  18. 'packages/common/src/',
  19. 'packages/admin-ui-plugin/src/',
  20. 'packages/asset-server-plugin/src/',
  21. 'packages/email-plugin/src/',
  22. 'packages/elasticsearch-plugin/src/',
  23. ],
  24. exclude: [
  25. /generated-shop-types/,
  26. ],
  27. outputPath: 'typescript-api',
  28. },
  29. ];
  30. generateTypescriptDocs(sections);
  31. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  32. if (watchMode) {
  33. console.log(`Watching for changes to source files...`);
  34. sections.forEach(section => {
  35. section.sourceDirs.forEach(dir => {
  36. fs.watch(dir, { recursive: true }, (eventType, file) => {
  37. if (extname(file) === '.ts') {
  38. console.log(`Changes detected in ${dir}`);
  39. generateTypescriptDocs([section], true);
  40. }
  41. });
  42. });
  43. });
  44. }
  45. /**
  46. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  47. * into markdown files
  48. */
  49. function generateTypescriptDocs(config: DocsSectionConfig[], isWatchMode: boolean = false) {
  50. const timeStart = +new Date();
  51. // This map is used to cache types and their corresponding Hugo path. It is used to enable
  52. // hyperlinking from a member's "type" to the definition of that type.
  53. const globalTypeMap: TypeMap = new Map();
  54. if (!isWatchMode) {
  55. for (const { outputPath, sourceDirs } of config) {
  56. deleteGeneratedDocs(absOutputPath(outputPath));
  57. }
  58. }
  59. for (const { outputPath, sourceDirs, exclude } of config) {
  60. const sourceFilePaths = getSourceFilePaths(sourceDirs, exclude);
  61. const docsPages = new TypescriptDocsParser().parse(sourceFilePaths);
  62. for (const page of docsPages) {
  63. const { category, fileName, declarations } = page;
  64. for (const declaration of declarations) {
  65. const pathToTypeDoc = `${outputPath}/${category ? category + '/' : ''}${
  66. fileName === '_index' ? '' : fileName
  67. }#${toHash(declaration.title)}`;
  68. globalTypeMap.set(declaration.title, pathToTypeDoc);
  69. }
  70. }
  71. const docsUrl = `/docs`;
  72. const generatedCount = new TypescriptDocsRenderer().render(
  73. docsPages,
  74. docsUrl,
  75. absOutputPath(outputPath),
  76. globalTypeMap,
  77. );
  78. if (generatedCount) {
  79. console.log(
  80. `Generated ${generatedCount} typescript api docs for "${outputPath}" in ${+new Date() -
  81. timeStart}ms`,
  82. );
  83. }
  84. }
  85. }
  86. function toHash(title: string): string {
  87. return title.replace(/\s/g, '').toLowerCase();
  88. }
  89. function absOutputPath(outputPath: string): string {
  90. return path.join(__dirname, '../../docs/content/docs/', outputPath);
  91. }
  92. function getSourceFilePaths(sourceDirs: string[], excludePatterns: RegExp[] = []): string[] {
  93. return sourceDirs
  94. .map(scanPath =>
  95. klawSync(path.join(__dirname, '../../', scanPath), {
  96. nodir: true,
  97. filter: item => {
  98. if (path.extname(item.path) === '.ts') {
  99. for (const pattern of excludePatterns) {
  100. if (pattern.test(item.path)) {
  101. return false;
  102. }
  103. }
  104. return true;
  105. }
  106. return false;
  107. },
  108. traverseAll: true,
  109. }),
  110. )
  111. .reduce((allFiles, files) => [...allFiles, ...files], [])
  112. .map(item => item.path);
  113. }